blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e24138fba2e6c2809f1f8907f8a97288eb590085
mivankin/algorithms
/numbers_permutations.py
576
3.859375
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 31 15:43:16 2020 @author: IVANKIN """ def find(number, A): for x in A: if number == x: return True return False def numbers_permutations(N:int, M:int=-1, prefix=None): M = N if M == -1 else M prefix = pref...
3d6268c001b2f4b7b273449e013c6088f9cdf705
python-practice-b02-006/magnetic-pool
/game.py
23,896
3.890625
4
import pygame import objects import data import numpy as np from main import WINDOW_SIZE, WINDOW_HEIGHT, BG_COLOR import matplotlib.pyplot as plt class Game: """Manages the game. Attributes: field: surface to which every game object is blitted. all_sprites: group that contains all game objec...
fca90a499a913a0f4488c49a3a0df033d2d8b242
samaeen/python_practice
/Arduino Basics/arduinoViz.py
473
3.78125
4
import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style style.use('fivethirtyeight') fig=plt.figure() ax1=fig.add_subplot(1,1,1) def animate(i): graph_data=open('sensorData.txt','r').read() lines=graph_data.split('\n') xs=[] ys=[] for line in lines: if len(line)>1...
0b841859ffc3ed84d183a4dc94036cb6cb915eef
Cuhwis/pyapi
/sort01/sorted03.py
346
3.578125
4
#!/usr/bin/env python3 simpsons = [('Moe', "?"), ('Otto', '?'), ('Lisa', 8), ('Bart', 10), ('Maggie', 2), ('Homer', 36), ('Marge', 34)] def take_second(secondplacewins): return secondplacewins[1] def sortbyagesandname(dataset): sortedbyages = sorted(dataset, key = take_second) print(sortedbyages) sor...
121f65cf78dae2d8d6a2487c1e3ca8d6dc3b0af5
sonicfigo/tt-sklearn
/sk0-quick-start/digits/l1_learn_by_fit.py
946
3.59375
4
# coding=utf-8 """ Choosing the parameters of the model fit函数 传入 training set,完成学习. """ from sklearn import datasets, svm digits = datasets.load_digits() def _create_classifier(): """ 创建一个分类器,并填充训练集-fit,进行学习。 """ # In this example we set the value of gamma manually. # It is possible to automati...
ac6d2d8cdbe637871ea41d25843559b69213122f
kevindubuche/dataStructure-algo
/mergeSort.py
826
4
4
# funct merge 2 arrays by sorting them import time startTime = time.time() def merge(ar1, ar2, len1, len2): i, j =0,0 res =[] while i <len1 and j < len2: if ar1[i] < ar2[j]: res.append(ar1[i]) i +=1 else : res.append(ar2[j]) j +=1 if i == l...
b76fa729542bb21e8ce7508d84e96aed95c34f52
Yash088/Algorithm-Toolbox
/week2/7.py
240
3.765625
4
def fibonacciNum(num,m): m = m % 60 a,b = 0,1 sum=0 for i in range(m+1): if( i >= num ): sum = sum + a a,b = b%10 ,(a + b)%10 print(sum%10) num,m=map(int,input().split()) fibonacciNum(num,m)
4e67b29b4c2861e1a3ddd14d6b804f9916ba0ea0
Yash088/Algorithm-Toolbox
/week2/4.py
348
3.65625
4
def gcd_euclid(a, b): dividend = a if (a >= b) else b divisor = a if (a <= b) else b while divisor != 0: remainder = dividend % divisor dividend = divisor divisor = remainder return dividend def lcm_fast(a, b): return (a * b) // gcd_euclid(a, b) a, b = map(int, input().sp...
59c8d18d40862fc713dc2d7dfe58c68c09dafe0f
weekstudy/fucking_the_algorithm
/test59_02_QueueWithMax.py
631
4.125
4
# -*- coding:utf-8 -*- class Queue(object): def __init__(self): self.elem = [] def push_back(self,x): self.elem.append(x) def pop_front(self): self.elem.reverse() self.elem.pop() self.elem.reverse() def max_value(self): # write code here if n...
09310a50b270e9c8f074cc808723cfc4d2a0b81c
weekstudy/fucking_the_algorithm
/test49_GetUglyNumbers.py
1,076
3.828125
4
# -*- coding:utf-8 -*- # 题目描述 # 把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数 # 但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。 # 求按从小到大的顺序的第N个丑数。 class Solution: def get_ugly_number_solution(self, index): # write code here if index < 1: return 0 time2 = [] time3 = [] time5 = []...
d30edc6795e1eaf1621014f9e3e82cbfd12b0166
weekstudy/fucking_the_algorithm
/test55_01_TreeDepth.py
1,336
4.0625
4
# -*- coding:utf-8 -*- # 题目描述 # 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的 # 结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度 class BinaryTreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def connect_tree_node(pRoot:BinaryTreeNode, pLeft:BinaryTreeNode=None, pRight...
a3ec861b2dee0c15372c53f361af3c0ffb562cc6
ambarishgurjar/interview
/trees.py
3,340
3.8125
4
# extended version of 'im-loving-tree.py' with Tree Class # to be worked on class Node: def __init__(self, data): self.data = data self.left_child = None self.right_child = None self.parent = None def __str__(self): return str(self.data) #is there a better way? def hasLeftChild(self): return self.left_...
3cb331c1f37cb15c405ade9d2041772b8b1aa516
ambarishgurjar/interview
/data-structures/im-loving-trees.py
4,724
3.671875
4
# Treeeeeeees! A special, dear type of graph # Duh duh duh duh duuuuuh, I'm lovin' dat graph theory # root node: 0+ child nodes # child: 0+ child nodes # no cycles # leaf: no children # Make sure to clarify tree/graph questions! # TREES # BINARY TREES: up to two children per parent node # BINARY SEARCH TREES--or...
233fd2c0f4247bab946ed6107851a956ea08edfd
ambarishgurjar/interview
/data-structures/stacks_n_queues.py
1,671
4.1875
4
# Stack: stack of data # LIFO ordering: last in, first out (most recent items: first items removed) # pop(): remove top item from stack | constant time # push(item): add item to top of stack | constant time # peek(): return the top of stack # isEmpty(): Return true iff stack is empty # no constant-time access to i...
42fbe2ddbd49c676f22dd63ecd4764d9ac5733c8
thomaskamalakis/telecomsystems
/lecture2/delta.py
433
3.625
4
import numpy as np import matplotlib.pyplot as plt def delta(t, Dt): x = np.zeros(t.size) for i, tm in enumerate(t): if -Dt/2.0 <= tm <= Dt/2.0: x[i] = 1.0/Dt return x Dts = np.array([0.1, 0.05, 0.025, 0.01]) t = np.arange(-0.2, 0.2, 0.001) plt.close('all') plt.figure(1)...
58037b0428301015bc332ef06b657bf0b1a6669f
thomaskamalakis/telecomsystems
/lecture2/myplotsinc.py
685
3.515625
4
import numpy as np import matplotlib.pyplot as plt # Time axis Npt = 1000 # number of points in the time axis T = 1e-9 # second T1 = 0.1e-9 # second # Frequency axis Npf = 1000 Fmax = 40e9 # Build time axis t = np.linspace(-T/2, T/2, Npt ) # Build frequency axis f = np.linspace(-Fmax, ...
d3c7365fd880731e34434144c0e8c1cf32fe96d9
OHTORO87/ai_homework
/python_0510_homework.py
1,482
3.984375
4
x = 10 under_20 = x < 20 print("under_20 : ", under_20) print("not under_20 : ", not under_20) #if 뒤에 불 값이 거짓인 경우 #명령문이 있어도 실행되지 않는다. if True: print("참입니다") if False: print("거짓입니다") #실행 안된다. # 조건문의 기본 사용 number = input("정수 입력>") number = int(number) if number > 0: print("양수입니다") ...
ff2703313ca01dad4d87f43cb6c860d5993f3ffb
nicklindgren/smart-gliders
/search/chainCodeSearch.py
3,386
3.765625
4
#!/usr/bin/env python def chainCodeTransform(matrix, m, n): # This function returns the chain code # transform of the m*n matrix argument transform = list() print 'Rows: {0}\n Columns: {1}'.format(range(0,n), range(0,m)) for row in range(n): print ' Row:{0}'.format(row) currTarg...
13d37779a9238fb5f472b8e5d9f62f7fdce7738d
muralimreddy/python3
/challanges/avoidObstacles.py
840
3.875
4
''' You are given an array of integers representing coordinates of obstacles situated on a straight line. Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer. Find the minimal length of the jump enough to avoid al...
3213d0c60d3da90d3097b25a24118290682ed50c
naomi-burrows/EMAT30008-Scientific-Computing
/simulate_ode.py
3,297
3.703125
4
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import root from math import nan import ode_solver def plot_time_series(ode, u0, t, labels=[], show=True): """ Plots the time series of provided ode for provided time interval. Parameters: ode (function): ode to plot th...
9c4fcd97b07dfd53aea0df83cf5a0f5a2b85e639
LFYG/pymarshal
/pymarshal/init_args.py
670
3.5625
4
""" """ import inspect def init_args(cls): """ Return the __init__ args (minus 'self') for @cls Args: cls: class or instance Returns: list of str, the __init__ arguments minus 'self' Raises: ValueError if __init__ does not have a 'self' argument "...
128fc3fad7b5d7d3ac466bf2cc4a6597845deda0
berquist/eg
/python/pickling.py
4,173
3.859375
4
"""Examples adapted from https://stackoverflow.com/a/41754104/3249688""" import copyreg import pickle class A: """Default getstate and setstate""" def __init__(self, i): self.i = i class Z: """Default getstate and setstate""" def __init__(self, i): self.i = i # copyreg.pickle(Z, l...
c7d813f263759fe09ac7caba02c5824677cbeb38
mshoemake3224/python-challenge
/PyBank/main.py
2,723
3.65625
4
import os import csv csvpath = os.path.join('..', 'PyBank',"Resources", 'budget_data.csv') with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') total = 0 months_total = 0 previous = 0 delta = [] max...
9410540544a5dc0daee0f60b1b6f42e97a6d02e9
Sigton/platforming-engine
/main.py
4,551
3.53125
4
''' Python Platforming Engine By Sigton Makes making games a lot easier :P ''' import pygame from pygame.locals import * import constants, spritesheet, platforms, level import player as p import sys def main(): ''' MAIN PROGRAM ''' # Init the mixer, then pygame itself pygame.mixer.pre_init(2...
16739e059ea94378d4054d26918be2170894dc20
ElizabethKon/Lesson1
/Lesson1 e4.py
426
4
4
#Задача 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. n = int(input('Введите целое положительное число ')) m = n % 10 n = n // 10 while n > 0: if n % 10 > m: m = n % 10 n = n // 10 print('Самая большая цифра в этом числе', m)
96705f8099881af2a00c869693dbb0d2f96cdacd
Kempie1/CodeBreaker
/codebreaker.py
2,192
3.5625
4
import random def generateCode(): code = [] for x in range(4): code.append(random.randrange(1,7)) return code def generateHint(guess,code): hint1=0 hint2=0 for x in range(len(code)): if guess[x]==code[x]: hint1+=1 else: try: ...
6a3395dc3531ba406665f9aeada2ac82912cbb23
malekelthomas/DataStructs_Algo
/queueTwoStacks.py
1,578
4
4
""" Implementing a Queue using Two Stacks """ from stack import Stack class MyQueue: def __init__(self): self.newestDataOnTop = Stack() self.oldestDataOnTop = Stack() def enqueue(self, data): self.newestDataOnTop.push(data) def dequeue(self): temp = Stack() if self.newestDataOnTop.isEmpty(): retur...
37deaec584b7254f2eaf96a93ebdb1aba64e2897
Garpur3/2020des9
/timee.py
1,008
3.71875
4
import time import datetime t0 = time.time() total_sum = 0 total_mul = 1 limit = 10000 for i in range(1,limit): total_sum += i total_mul *= i print(f'For the first {limit} number\nTotal sum: {total_sum}\nTotal multiple: {total_mul}') t1 = time.time() limit = 100000 for i in range(1,limit): total_sum += i ...
d82f62d587a289a799526e9f8aae0051d2adaa1b
alexmadon/atpic_photosharing
/python/atpic/authenticatesql.py
2,115
3.546875
4
#!/usr/bin/python3 """ Authenticates at login with a user/password. This is different from the session based authentication. Once a session is created no SQL query is necessary But to create a session, we need a SQL lookup with username and password. """ # import logging import atpic.log import atpic.authenticatecrypt...
ebe15e36424808e66a5adba8f5c7dfd2b3f8fbcf
dileep-kishore/advent-of-code-2020
/day02/day02.py
2,693
4.21875
4
#!/usr/bin/env python3 from collections import Counter from typing import Tuple class Password: """ The `Password` class Could store invalid passwords Parameters ---------- password_string : str Attributes ---------- policy : str The policy password : str The...
360339a6f788840c4877a48fafb4302aac07f224
jeffrelt/interviewbit
/trees/PREFIX.py
1,231
4
4
''' PREFIX Find shortest unique prefix to represent each word in the list. Example: Input: [zebra, dog, duck, dove] Output: {z, dog, du, dov} where we can see that zebra = z dog = dog duck = du dove = dov NOTE : Assume that no word is prefix of another. In other words, the representation is always possible. ''' cl...
e492925b644272a52e53478669f2dd73cf9fb817
jeffrelt/interviewbit
/linked_lists/REVERSELIST.py
1,418
4.3125
4
''' REVERSELIST Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list. Note 2: Usually the version often seen in the interviews is r...
1f21af9fd65465199b7a66537b4748500e3a98a3
vkrbt/algorithms_python
/depth_first_search/labyrinth/labyrinth.py
2,764
3.59375
4
from random import randint SIZE = 20 class Cell: def __init__(self, column, row): self.column = column self.row = row self.top = True self.left = True self.bottom = True self.right = True self.visited = False def __str__(self): return ('colum...
54d716491177b3710f1f7a0e3d2701b1110e9597
phstearns/test1
/test1x1.py
325
3.6875
4
print("Welcome") print("to test program 1x1") print("Hello, World!") c= input("input number: ") c=float(c) print(c) a= 15 print("a=15") b=37 print("b=15") print("a+b=") e=print(a+b) print("a+c=") f=print(a+c) print("b+c=") g=print(b+c) print("a-b=") h=print(a-b) print("a-c=") i=print(a-c) print("b-c=") j=print(b-c) pri...
3a5858f82303445d44de6ccddb396fc9d11208bf
Tudi/TempStorage
/PythonTutorials/Day2_ex/day2_ex5.py
99
3.5625
4
l = ["a", "b", "c", "d"] OutDict = {} for elem in l: OutDict[elem] = ord(elem) print(OutDict)
23b3521c023a7b2546d59f9b5e2bcaf110c3aa47
Tudi/TempStorage
/PythonTutorials/Day3_ex/Day3_ex5.py
171
3.953125
4
def filter_short_words(word_list, n): return list(filter(lambda x: len(x) < n, word_list)) words = ['abraca', 'dabra', 'a', 'b'] print(filter_short_words(words, 3))
69b5c71036f1397c053997a4ca0058f8f521e528
Tudi/TempStorage
/PythonTutorials/labdafunctions.py
1,097
3.609375
4
mysum = lambda x, y: x + y def mysumx(x, y): return x + y print(mysum(1, 2)) print(mysumx(1, 2)) wordlist = ['hello', 'world', 'bye', 'hi'] print(min(wordlist)) min_str = min(wordlist, key=len) print(min_str) min_str = min(wordlist, key=lambda word: word[1]) print(min_str) value_list = [1, 2, 3, 4, 5, 6, 7]...
f3b370b0e09eea29c31270914e414eb6dc12e441
Made-of-Dark-Matter/DSA-Algorithms_on_Graphs
/2-1-my_toposort_1.py
1,392
3.84375
4
#python3 #Reachability of graphs #implementing a graph vertex using adjacency List import sys class Vertex(): def __init__(self, value, visited = False): self.value = value self.visited = False self.CCnum = None self.N = [] #Neighbours self.pre...
448e831a6e73b855dd5ac6b09d9481db53353e38
deains/scoreboard
/score/sevensegdisplay.py
15,306
3.546875
4
from gpiozero import LEDCollection, LEDBoard, OutputDeviceError, DigitalOutputDevice from gpiozero.threads import GPIOThread from gpiozero.exc import OutputDeviceError from itertools import cycle from time import sleep class SevenSegmentDisplay(LEDBoard): """ Extends :class:`LEDBoard` for a 7 segment LED displ...
d85279c889163ebab39945a6bbaac912799b814d
A1zak/Lab-8
/Zad2.py
812
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Создайте словарь, где ключами являются числа, а значениями – строки. # Примените к нему метод items(), c с помощью полученного объекта dict_items создайте # новый словарь, "обратный" исходному, т. е. ключами являются строки, а значениями – # числа. if _...
df410dd10070df6d60b85f197d160fa9d63307fc
ColorCloud/common-utils
/common/utils/page_utils.py
694
3.609375
4
# -*- coding: utf-8 -*- ''' Created on 2017-03-20 @author: lishiwei ''' from math import ceil from .errors import raise_error def paginate(data, per_page): """Paginate one list, return one iterator params: data : paginated data per_page: page size of per page returns: one iterator ""...
4f50ab1e20ca8dea35b1437ce70a6f6394cc3758
nandanaajayan/Class-Assignment-1---Getting-Started-with-Python-Programming
/conditional exercise.py
430
4.28125
4
name = 'John Doe' len_name=len(name) if len_name > 20: print('Name "{}" is more than 20 chars long'.format(name)) elif len_name > 15: print('Name "{}" is more than 15 chars long'.format(name)) elif len_name > 10: print('Name "{}" is more than 10 chars long'.format(name)) elif 8 >= len_name <= 10: print...
d21fb36d9cfcf45cbf055e7d50c3a240abfbe63f
SebastianSebz/SebastianSuarez_hw9
/SebastianSuarez_GenerarTiempos.py
620
3.71875
4
import numpy as np import time #Se define la funcion de fibonacci def fibonacci(N): #Caso1 if (N == 1 or N==0): return N #caso recursivo else: return fibonacci(N-1) + fibonacci(N-2) #Pruebas #print fibonacci(0) #print fibonacci(5) #print fibonacci(10) t0 = time.time() #Se define la funcion que toma el ti...
5cde8cfd426e678a1bdc1cd0077628d6f3c61f8a
Code-Kartikey12/aws_my_git
/String_formating.py
407
3.59375
4
import random age = random.randrange(25,85) name = 'Kartikey' #for python 3.6 and above print(f"Age of {name} is {age}"); # print("\nAge of "+name+" is "+age) <- this will give error unlike C #for python 3.6 and below print("Age of {} is {}".format(name,age)) x = 0 for i in name: print(f"{name} and {x} "...
69412970a160197e742c2975e186229482e2739c
ArtemLunin/python_lessons
/13.py
688
3.625
4
from datetime import date, datetime, timedelta import time # 13.1 # print(datetime.now()) now = datetime.now() now_str = now.isoformat() with open('today.txt', 'wt') as output: # print(now_str, file=output) output.write(now_str) # 13.2 with open('today.txt', 'rt') as input: today_string = input.read() # 13.3 # fm...
af76ed4cb121dcdc558a39ac3c97dc6faa6959ba
ArtemLunin/python_lessons
/6.py
368
4.25
4
# после цикла while, for может использоваться проверка как он завершился , если break не было, то после цикла запустится блок else # list(range(0, 100, 5)) - создает последовательность от 0 до 100 с шагом 5 for x in range(3, -1, -1): print(x)
c6a070ada7f01eb6aeff0a3cff6859f20e9c1447
Islanderrobotics/Islander_Stock_Analysis
/islander_stocks.py
2,898
3.65625
4
import os import queue import threading from price import Price,StockDoesNotExistError from getting_the_data import GettingTheData from islanderqueue import IslanderQueue class Islander_stocks: '''the purpose of this class is to allow the user to see all of the current stocks that are less then or equal to there maxi...
f123dbe3aaf76dd2f7943b9e90ab160dcc617da6
dshue20/interview-prep
/python/coinChange.py
1,209
3.953125
4
# You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. # Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. # You may ass...
65375cf9e4af59909a7af9820f788a932eb4dc48
dshue20/interview-prep
/python/bsearch.py
496
3.578125
4
import math class Solution: def search(self, nums: List[int], target: int) -> int: if not len(nums): return -1 midpt = math.floor(len(nums)/2) midnum = nums[midpt] if midnum == target: return midpt elif midnum > target: return self.search(nums[:midpt],...
372c7f00eeee2091504847a5539ff46e6d6e6552
dshue20/interview-prep
/josi.py
145
3.5625
4
def missing_num(arr): set = {} for i in range(len(arr)): set.add(arr[i]) for i in range(len(arr)): if (!(i in set)) return i
222c4a19a1c68f691b56794a912318deff7a0ecf
ishantk/GW2020P1
/Session18.py
837
4.0625
4
""" Modules in Python Any Python Program is known as MODULE :) """ # In a Python Module we create code: print("1. This is Session18") print("1. Session18 __name__ is:", __name__) name = "John Watson" def add(num1, num2): result = num1 + num2 print("Result is:", result) class User: def __init__...
c063957409f2283200924aa5ad2243fbb66050fd
ishantk/GW2020P1
/Session6.py
840
4.21875
4
""" Functions in Python We can have a case where out piece of logic needs to be executed again and again Use Case: Taxes on products needs to be computed at many places in an e-commerce platform 1. When we show the product Prices 2. When we Show th Cart Value 3. When we Chec...
94b6fd345deb0cdce814c0f94008259845327012
ishantk/GW2020P1
/Session6F.py
757
4.4375
4
# Recursion : Function Executing Itself again and again for i in range(1, 11): print(">> i is:", i) # Functions can produce the same results, which loops can with recursion print("~~~~~~~") def printNumber(number): # a breaking point with return statement if number > 10: return print(">> nu...
edf45a1c186071f4fd52560297ef66e231381777
ishantk/GW2020P1
/Session3C.py
395
3.5
4
johnsFollowers = {"kia", "sim", "leo", "mike", "dave"} fionnasFollowers = {"john", "kia", "lee", "Ana", "mike", "dave"} # Mutual Friends/Followers mutualFollowers = johnsFollowers.intersection(fionnasFollowers) print("JOHN") print(johnsFollowers, len(johnsFollowers)) print("FIONNA") print(fionnasFollowers, len(fionn...
0707042dc215255cb00f38369ef829ed0b4057d3
ishantk/GW2020P1
/Session10B.py
501
4.21875
4
def add(num1, num2): sum = num1 + num2 print("sum of {} and {} is {}".format(num1, num2, sum)) print("add is created and its details are:", add) # PS: If we re-create the same function again, # Old one will be deleted from memory and new one is in action def add(num1, num2, num3): sum = num1 + num2 +...
91500737db690bfa4d9d6bb9e0cac9d7e24b581c
ishantk/GW2020P1
/Session26.py
721
4.0625
4
""" Data Visualization with Matplotlib https://matplotlib.org/ """ # import matplotlib as lib # print(lib.__version__) # to check the installed version of your library import matplotlib.pyplot as plt """ data = [0, 1, 2, 3, 4, 5] plt.plot(data) # plot plots a line graph plt.show() """ X = list(range(0, 11)...
c723926193d5549ea721638709498e10a33fe5f5
ishantk/GW2020P1
/Session10I.py
872
4.375
4
def get_max_number(data, length): if length == 1: return data[0] # for elements in list with length 1, that element itslef is the max which is 0 index else: num = get_max_number(data, length-1) if num > data[length-1]: return num else: return data[length-1] numbers = ...
8364652ebb719e5452598f8ce0b5189b5421be8b
ishantk/GW2020P1
/Session8G.py
862
3.71875
4
""" Image is a collection of Pixels Pixel is RGB Value [ranges from 0 to 255] For rgb colors reference: https://www.w3schools.com/colors/colors_picker.asp?colorhex=ff0c14 """ # R G B pixel1 = [120, 50, 90] pixel2 = [235, 50, 90] pixel3 = [128, 45, 90] pixel4 = [180, 50, 90] pixel5 = [175, 32, ...
d1c7342cd70d32a43797ee4aca476a502a0cd57f
ishantk/GW2020P1
/Session6C.py
411
3.625
4
# Function Execution Stack # Whenever we execute function, in the background stack operations comes in action def computeTaxes(amount): taxes = 0.18 * amount total = amount + taxes return total # Slope of Line: y = mx + c def slopeOfLine(m, x, c): y = m*x + c return y # execute the functions pri...
c7e67402418367eace4403cefd8f5f1cae2e510a
ishantk/GW2020P1
/Session20F.py
973
3.78125
4
import os print(os.name) print(os.uname()) print(os.getlogin()) print(os.getppid()) # Process Id in which this program is getting executed print("Current Working Directory:", os.getcwd()) path_to_directory = "/Users/ishantkumar/Downloads" path_to_file = "/Users/ishantkumar/Downloads/key.json" print("Downloads Direc...
4130b0df03565479105ef1f0beb2d67b71d93859
ishantk/GW2020P1
/Session15A.py
2,388
3.8125
4
menu = { 101: 30, # Samsosa 201: 50, # Tikki 301: 100,# Noodles 401: 120,# Burger 501: 150 # Manchurian } class Order: # This variable is created in the class and belongs to class # accessible by class name and is not the property of object order_id = 0 def __init__(self): ...
8ecb3214097d85e0010bce70745a950010bbc762
ishantk/GW2020P1
/Session20E.py
1,332
4.21875
4
# We can create our own Exception Classes also # User Defined Exceptions class BankingError(Exception): def __init__(self, message): Exception.__init__(self, message) class BankAccount: # If any user opens up a bank account # default balance is 10000 def __init__(self): self.balance =...
5106a7c1113ce367a3c48e26b3460db56211aa82
nghiahsgs/calender-note-vue-js
/api/utils.py
903
3.859375
4
import datetime def nb_day_in_a_month(month,year): leap = 0 if year% 400 == 0: leap = 1 elif year % 100 == 0: leap = 0 elif year% 4 == 0: leap = 1 if month==2: return 28 + leap list = [1,3,5,7,8,10,12] if month in list: return 31 ...
927d1d5e2fcb92571cc272d0f2610338dbb3d3d8
johnvanmeerten/TiCT-VIPROG-15
/Les08/Oefening 8_1.py
488
4.03125
4
set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7} set3 = {1, 2} print(set1.union(set2)) #vult aan print(set1 | set2) print(set1.intersection(set2)) # alleen wat in beide zit print(set1 & set2) print(set1.difference(set2)) #wat wel in de ene voorkomt maar niet in de andere print(set1 - set2) print(set2 - set1) print...
4f4d5bdc923ed74f8ea8146816ca25e29fff1220
johnvanmeerten/TiCT-VIPROG-15
/Les06/Practice 6_1.py
303
3.5
4
def seizoen (getal): if getal >= 3 and getal <= 5: return ('lente') elif getal >= 6 and getal <= 8: return ('zomer') elif getal >= 9 and getal <= 11: return ('herfst') else: return ('winter') getal = eval(input('Geeft getal op: ')) print(seizoen(getal))
21c2d78cfb341691ab93e7c0c3ca44067868e5ab
johnvanmeerten/TiCT-VIPROG-15
/Les09/ExtraOpdracht 4_7.py
554
3.640625
4
def berekensomevengetallen (getallenrij): som = 0 for getal in getallenrij: if getal %2 == 0: som += getal return (som) def berekensomonevengetallen (getallenrij): som = 0 for getal in getallenrij: if getal %2 == 1: som += getal return (som) getallenri...
dfe6f3d0187beacaa327db4798b0fc3fa2cd4e7d
johnvanmeerten/TiCT-VIPROG-15
/Les08/Practice Exercise 8_1.py
216
3.578125
4
set1 = {'boxtel', 'best', 'eindhoven', 'helmond t hout', 'holmond', 'helmond brouwhuis', 'deurne'} set2 = {'boxtel', 'best', 'eindhoven', 'geldrop', 'heeze', 'weert'} print(set1 | set2) print(set1 - set2) print(set1 & set2)
1bec5ac1a74dca2235f3a0e8094b23003b94dbfc
johnvanmeerten/TiCT-VIPROG-15
/Les05/Practice 5.1.py
189
3.75
4
def convert(c): f = c * 1.8 + 32 return f def table (): print(' F C') for f in range(-30, 41, 10): print('{:6.1f} {:6.1f}'.format(convert(f), f)) table()
d5f12912fabdac791c80d15b98947c5dea3cea2e
johnvanmeerten/TiCT-VIPROG-15
/Les04/Perkovic 3.33.py
111
3.609375
4
def reverse_string(x): nieuwwoord = x[2] + x[1] + x[0] return nieuwwoord print(reverse_string ('abc'))
5065390d46d96f2f4cb93505fb380b976bce971c
johnvanmeerten/TiCT-VIPROG-15
/Les03/Perkovic 3.23.py
231
4.09375
4
for i in range(0, 2, 1): print(i) for i in range(0,1,2): print(i) for i in range(3, 7, 1): print(i) for i in range(1, 2, 1): print(i) for i in range(0, 4, 3): print(i) for i in range(5, 22, 4): print(i)
ccf7ba216084027037f6dc8dab7edd3e8f24d902
jmelton15/Python-Console-BlackJack
/blackjackMoney.py
1,538
3.5625
4
import colorama from colorama import Fore, Back, Style class Chips: def __init__(self): self.total = 50 self.bet = 0 def win_bet(self): self.total += self.bet def lose_bet(self): self.total -= self.bet def blackjack(self): self.total += (self.bet + (self.bet*.5)) def bet(chips): ...
741ed7e326bb9bcc333ae0b4ff4b1ab917f83f88
RoseLV/data-analytics-Girffith-University
/sql_temp.py
1,351
3.796875
4
import sqlite3 # Connect database temperature conn = sqlite3.connect('temperature.db') sql = conn.cursor() # Create table Southern_cities and drop if exists sql.execute('drop table if exists Southern_cities;') sql.execute("""create table Southern_cities(city text, country text, latitude text, longitude text)""") # L...
f117f3501eb85404859f7b1127b13228ef30ca4f
webNeat/performance
/primes/main.py
261
3.9375
4
from math import sqrt def isPrime(n): for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True found = 0 count = int(input()) n = 0 for i in range(count): n = int(input()) if isPrime(n): found = found + 1 print(found)
005308bf8ffb538caf30fffbe1edc5e520f94b69
ReginaldM/Python-Exercises
/List Comprehension.py
320
3.96875
4
import random """ Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. """ listA = random.sample(range(1,100),50) print(f"{[i for i in listA if i%2==0]}")
00c93236649c3759639f0e66bb6981e616893a4b
ishashukla183/CP_Snippets
/Python/hamiltanion_cycle.py
1,818
3.796875
4
''' USERNAME: oldschool8051 DESCRIPTION: Program to Determine whether a given Graph Contains Hamiltonian Cycle or Not. DATE: 2/10/2021 ''' class cycle(): def __init__(self,vertices): self.graph=[[0 for column in range(vertices)] for row in range(vertices)] s...
b8d708d1c487172073c4bcbdba659b0efb7a1776
wawerualbert/coffee_machine
/coffee_machine.py
4,429
4.375
4
# Write your code here class CoffeeMachine: print("********** Welcome to Starbucks Coffee *********") print("Your one stop shop for great cup of coffee :)") print("We offer 3 different types of coffee") print("Our menu List:") print("Type Cost") print("Espresso .............$4 "...
240e8efb5510d3d0354f8f832eb50334423c4429
torontowhizkid/learn-python
/magic8ball.py
674
3.765625
4
import random print("Welcome to Magic 8!") magic8_answers = ["It is certain.", "It is decidedly so.", "Without a doubt.", "Yes – definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask a...
572a38543f2e243f8283719a6e026bb5e5fc51a0
shenberg/tbbot
/tb_image.py
4,353
3.828125
4
import Image import sys import match_letter LETTER_SIZE = (25,30) MIN_WIDTH = 6 # Translate the color white (255) to a blank pixel (0) # and the color black (0) to a letter pixel (1) def xlate_col(col): if col == 255: return 0 return 1 def find_confirmation_code(code): confirmation_code = '' letter_num = 0 c...
d54c11ed058fd64ea468260cad7b33533226b047
posttwo/seedsync
/src/python/system/file.py
1,015
3.671875
4
# Copyright 2017, Inderpreet Singh, All rights reserved. from typing import List class SystemFile: """ Represents a system file or directory """ def __init__(self, name: str, size: int, is_dir: bool = False): if size < 0: raise ValueError("File size must be greater than zero") ...
22dbeb4a0ea45ca382c828022e3bf5f4ab9d34c1
Pavankumartrivedi/details_collector_using_tkinter
/details.py
1,359
3.703125
4
from tkinter import * root = Tk() def getvals(): print("Details Recieved") print(f"{namevalue.get(),Agevalue.get(),cityvalue.get(),Blood_groupvalue.get()}") with open("records.txt", "a") as f: f.write(f"{namevalue.get(),Agevalue.get(),cityvalue.get(),Blood_groupvalue.get()}\n ") Label(root, text="F...
e266a068bfd7f8117743d70c418b32021d184752
HarshitGulgulia/SMVIT_CODE_IT
/Vote.py
162
4.21875
4
Age=int(input("Enter your age ")) if Age>18: print("Eligible to vote") elif Age==18: print("Eligible to vote") else: print("Not Eligible to vote")
e0d92d3a309dc50a31044fdd38d028ca1199b83d
Anisha7/Cracking-the-coding-interview
/recursion.py
2,407
4.15625
4
# 1. Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 # steps at a time. Implement a method to count how many possible ways the child can run up the # stairs. def tripleStep(n): memo = dict() for i in range(n+1): memo[i] = 0 return tripleStepHelpe...
ef3762d36c73e7575917f4382813287aded7e16f
Anisha7/Cracking-the-coding-interview
/object-oriented-design/callcenter.py
1,434
3.78125
4
# Call Center: Imagine you have a call center with three levels of employees: respondent, manager, # and director. An incoming telephone call must be first allocated to a respondent who is free. If the # respondent can't handle the call, he or she must escalate the call to a manager. If the manager is not # free or not...
82d4f2a2856bcc8633db73831eef002c97990bd2
kmalakhova/Introduction_to_Python
/string_slicing.py
527
4.0625
4
''' Copeland’s Corporate Company also wants to update how they generate temporary passwords for new employees. Write a function called password_generator that takes two inputs, first_name and last_name and then concatenate the last three letters of each and returns them as a string. ''' first_name = "Julie" last_name...
a420d051b86c84d89708c06e7978df4200510101
adammjaffe/projects
/Python/Assignment 5/bulls_and_cows1.py
1,683
3.96875
4
# Adam Jaffe # amj2158 # February 21, 2013 # Professor Cannon # file: bulls_and_cows.py # This program plays the game "Bulls and Cows." def number_generator(): ' ' 'This creates a random 4-digit number/list with no repeating digits' ' ' again=0 import random as r while(again==0): w=r.randrange...
62de4f6bfd9584f0a324ad395d716b1d8c992cac
adammjaffe/projects
/Python/Assignment 4B/Percolation.py
8,308
3.84375
4
def boolean_converter(np,N,infile): '''This converts a .txt file of 1s and 0s into an array of True and''' \ '''False values''' # Create an 'empty' 1D array of the appropriate size. file_array=np.zeros((N,N),bool) # For each of the remaining rows in the square matrix, read a line and ...
f71b7a152cb8c48d8c0a0857508eaa18af1f74ce
Easoncyx/AI_Assembly_Puzzle
/assembly_puzzle.py
3,845
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # DFS version # In[1]: import numpy as np # one way to do the rotation def rotate90_counterclockwise(matrix): for i in range(len(matrix)//2): for j in range(len(matrix)): tmp = matrix[j][i] matrix[j][i] = matrix[j][len(matrix)-i-1] ...
1391a413248e76f30bb9e814f7acb94ec20dc32f
kaleidoscopica/adventofcode2020
/Day4/4-1.py
1,404
3.9375
4
def main(): passports = [] valid_passport_count = 0 # Populate the initial passport list from our input file with open('input.txt') as file: passports = file.read() passports = passports.split("\n\n") #creates a separate item in the list passports = [item.replace('\n', ' ') for i...
d0d84d1c2466644bf70ea933da7c558479502f79
Jak2/Practicing_the_basics
/Python/for_loop.py
1,279
4.25
4
#* for number in a list means #* number = alist and this runs in loop that's all #* for better understanding #* see this n2 for n from 0to5 program down this line alist=[1,2,3,4,6] number=3 #* this is a number but alist is a list for number in alist: print(number) #* n2 for n from 0to5 for n in [0,1,2,3,4...
8c2fb51f37597498fdd40264aa9dcc5e91a1031a
Hitherto-crypto/Handsonpython
/strings.py
1,259
4.0625
4
'personal cars' #single quotes print('personal cars') 'doesn\'t' #use \' to escape the single qoute... print('doesn\'t') '"Yes," they said.' print('"Yes," they said.') "\"Yes,\" they said." print("\"Yes,\" they said.") s='First line.\nSecond line.' #\n means newline s #without print(), \n is included in the ...
6125845a7509b0388228eb1689776c7d6be34ba5
Ronney31/coding
/Codechef-Question/CodeChef_factorial.py
366
3.578125
4
#https://www.codechef.com/problems/FLOW018 ''' for _ in range(int(input())): no = int(input()) fab = 1 for i in range (2,no+1): fab*=i print (fab) ''' #rec for _ in range(int(input())): no = int(input()) def fab (n): if n == 0 or n==1 : return 1 ...
f5b708058bcd532a902248e49b1d729cd1abedfe
Ajitsingh26/python_assignment
/question1.py
139
3.515625
4
list=[] for number in range(2000 , 3201): if (number % 7==0 and number% 5 !=0): list.append(str(number)) print (','.join(list))
4d13a240c5dc1108d2f75b545124a5775d08e186
shellyalmo/Python-Track---She-Codes
/Lists and Strings/bulls_and_cows.py
1,694
4.03125
4
"""player 1 has to guess a 5 letter string, within the least number of rounds. in each round player 1 guesses a string and gets : how many "bulls" = correct guesses of letters and in correct location, how many "cows" = correct guess but wrong location """ import string import random def bulls_and_cows(real,guess): ...
92b4e1249c73d8a7d7b5a00efcec27dbff80f0e9
shellyalmo/Python-Track---She-Codes
/Lists and Strings/classwork2.py
562
4.375
4
# write a function that accepts a string and produces a dictionary # that connects between an alphabet letter to the number of times it appears # in the string. # for example calling char_freq("abzz") will return the dictionary: # freq = {'a':1, 'b':1, 'z':2} def frequency_of_letters(some_string): the_alphabet = ...
c695c3c4852a5430ab71ac574e02ac2d2a7879ac
shellyalmo/Python-Track---She-Codes
/Pythonic way of code/classwork_pythonicway.py
2,692
4.46875
4
""" In front of you are two lists.first belongs to first and so on. 1 ) write a single line of code that creates a list in which every item is the name of a movie and the actress that plays in it: Gone Girl is played by Rosamund Pike """ movie = ['The Notebook', 'Maleficent', 'Batman V Superman', 'Black Swan','Gone Gri...
6d35bafca0ee3d27e8c847d5aa31e0d1e9d4272e
gdjeudeu/python-challenge
/PyBank/main.py
2,120
3.546875
4
import os import csv csvpath = os.path.join('Resources', 'budget_data.csv') with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = next(csvreader) #The total number of months included in the dataset counter = 0 counter_2 = 0 largest = 0 small...
f65a936aa3e196f4c5b814d1a64bd1e1c85f6039
IAmBullsaw/oskarjanssondotcom
/card.py
1,870
3.546875
4
class Card: """ The class to hold the information for a project or similar """ def __init__(self, cid, title, description, headerhref, headeralt, content): """ Checks for correct parameter types and sets images to default if none passed """ # message = 'Failed to initialize Card: ' # TOD...
5a7812e62d33ccea2f9ebcb3dda26053424ec87e
ZiningZhu/IEEEXtreme10
/countMolecules/countMolecules.py
783
3.578125
4
def main(): line = str(input()).split(" ") c = int(line[0]) h = int(line[1]) o = int(line[2]) z = [c, h, o] M = [[-24, 6, 12], [0, -6, 12], [4, 1, -2]] x = my_multiply(M, z) x = vector_divide(x, 24) possible = True for k in x: if (k != int(k)): possible = Fals...
2b13f3561eb8f3d732535759125bccf0d72fb6cf
ZiningZhu/IEEEXtreme10
/Ellipse/Ellipse.py
1,421
3.578125
4
import math import matplotlib.pyplot as plt def main(): T = int(input()) for t in range(T): canvas = [[0] * 100] * 100 N = int(raw_input()) for n in range(N): line = raw_input().split(" ") x1 = int(line[0]) + 50 y1 = int(line[1]) + 50 x2 =...
f1104b53b09f9ae447f03c1d0f8ba335e8c153c2
QuietMouse1/CS50pset
/pset6/readability.py
884
3.84375
4
from cs50 import get_string # Coleman-Liau index is computed as 0.0588 * L - 0.296 * S - 15.8, # where L is the average number of letters per 100 words in the text, # and S is the average number of sentences per 100 words in the text. end_of_sentence = ["?", "!", "."] s = get_string("Text: ") number_of_sentences = ...