blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f85fc9cb733037fb4d27637a9389c7a36216f818
rpryzant/code-doodles
/interview_problems/2018/CRACKING/4.7_v2.py
1,535
3.765625
4
""" given a list of tuples are we guarenteed that this is a tree? (i.e. that it has a single root?) no self loops? yes (child parent) give a bfs traversal of the resulting tree eg [('d', 'a'), ('b', 'f'), ('d', 'b'), ('a', 'f'), ('c', 'd')] output: f e a b d c STEPS 1) build tree (+ get root) {node: [its chil...
04d64f1b7f5a3a63baac0883450f76aaa6f88c34
rpryzant/code-doodles
/sorting_algos/quicksort.py
541
3.625
4
def swap(a, i, j): tmp = a[i] a[i] = a[j] a[j] = tmp def sort(a): return sortR(a, 0, len(a) - 1) def partition(a, low, high): pivot = a[high] i = low for j in range(low, high): if a[j] <= pivot: swap(a, i, j) i += 1 swap(a, i, high) return i def s...
3fc56c8ddd1edd7693992893986dbdd350a5015d
rpryzant/code-doodles
/interview_problems/2018/triangle/triangle2.py
830
3.75
4
# -*- coding: utf-8 -*- """ negatives? guarenteeed well formed triangle? just sum, or whole path? (just sum) 1 enumerate all paths (dfs) take max 2 dijkstras? 3 some kind of dp thing? def gen_path_sums use dp to traverse this tree def max sum iteratively update max (to save on space) """ import sys def min_s...
7a31f9c0909d42febe292d7bb51b1e1a6fc2d24a
rpryzant/code-doodles
/interview_problems/2018/add_two_nums/adder.py
860
3.78125
4
# in notes class Node: def __init__(self, d): self.next = None self.data = d def append(self, x): n = Node(x) r = self while r.next is not None: r = r.next r.next = n def __str__(self): s = '' r = self while r is ...
6ba714b0ae4a9e937f1cc153f0b7d9bca0dbfa4c
rpryzant/code-doodles
/interview_problems/2018/interleaving_strings/interleaving.py
911
3.734375
4
# i like my solution to this one! def is_interleaving(s1, s2, s3): def ii(s1, s2): m, n = len(s1), len(s2) if not len(s3) == m + n: return False if s1 is '' and not s2 == s3: return False if s2 is '' and not s1 == s3: return False if s3 is...
5e71cce75be735d7fcf99d2b020a65e8fb495454
rpryzant/code-doodles
/interview_problems/2018/strstr/strstr2.py
260
3.734375
4
def substr(s, sub): sub_hash = hash(sub) for i in range(len(s) - len(sub)): if hash(s[i:i+len(sub)]) == sub_hash: return i return -1 t = 'one two three' print substr(t, 'two') print substr(t, 'five') print substr(t, '')
caf032e79c85575d5dd6b28a5f34bb5aae114ef3
rpryzant/code-doodles
/purely_random/quora/make_tree_from_inorder_preorder.py
724
3.84375
4
""" Given a preorder and inorder traversals of a binary tree with unique numbers, reconstruct the original tree, and return a pointer to the root node. Analyze runtime and space complexity 3 5 2 6 1 4 6 5 3 2 4 1 """ def makeTree(inorder, preorder): if not inorder or not preorder: return No...
498e130585a36c02206019e70d4dc9e2a03c4d45
rpryzant/code-doodles
/interview_problems/2018/CRACKING/16.6.py
805
3.5625
4
# in notes def smallest_diff(A, B): A = sorted(A) B = sorted(B) ai = bi = 0 min = None while ai < len(A) - 1 and bi < len(B) - 1: if not min or abs(A[ai] - B[bi]) < abs(min[0] - min[1]): min = A[ai], B[bi] if ai < len(A) - 1 and A[ai] <= B[bi]: ai += 1 ...
3afd56dbb9f381296128188603c1dbee6e7e2eb2
rpryzant/code-doodles
/interview_problems/2018/n_queens/queens.py
889
3.65625
4
def draw_board(cols, n): out = [] for col in cols: out.append( ('.' * (col - 1)) + 'Q' + ('.' * (n - col)) ) return out def valid(col, cols): # you know the row is new so no hit there row = len(cols) for r, c in enumerate(cols): # same col if col == c: retu...
57528ca3eb770eb3abb3c3627e3c073d4764c301
rpryzant/code-doodles
/interview_problems/2018/CRACKING/17.12.py
1,234
3.859375
4
class binode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def printpretty(self): self.__printpretty(self.root, "") def __printpretty(self, node, s): if node: self.__printpretty(node.right, s...
1c0b3ef3ced434b10f9743f0d9c9555a1d0e5b1c
rpryzant/code-doodles
/interview_problems/2018/CRACKING/3.2.py
729
3.71875
4
class Stack: def __init__(self): self.s = [] self.mins = [] def push(self, n): self.s.append(n) if not self.mins or n < self.mins[-1]: self.mins.append(n) def pop(self): if not self.s: return None if (len(self.s) == 1) or (self.s[-2...
f49ccf9dff85bfa4b7f42c5feb4f9f26b8fcb9b7
rpryzant/code-doodles
/interview_problems/2018/word_ladder/ladder.py
1,517
3.609375
4
""" ====BF 1) read in /usr/share/dict into hashmap 2) bfs on that - structure which gives all words 1 edit distance away ====BETTER? 1) read words into trie ===bfs 1) method that gives all possible successors (done under the hood somehow) 2) bfs on that (bidirectional) """ from Queue import Queue class Wo...
6ea375bd6a4c70d0b95d3677d8503d68230616d0
rpryzant/code-doodles
/purely_random/snapchat/snap2.py
1,068
3.625
4
log s1 s2 … sn return k most frequently occuring strings in this log IDEAS shrink problem sort list, find adjacents O(n log n) get word freqs, then use heap word freqs is O(n) time (& space) use heap to track top k heaps? max? min? if max, then biggest is at top of list heaps have depth of log_2(len(h) ...
c8ef05816a7f350df62c9451d1f03b23fb9daddf
rpryzant/code-doodles
/interview_problems/2018/merge_sorted_arrays/merge.py
371
3.75
4
def merge(a, m, b, n): if m < 0 or n < 0 or a is None or b is None: return a ai = bi = 0 while bi < len(b): if b[bi] <= a[ai]: a.insert(ai, b[bi]) m += 1 bi += 1 elif ai >= m: a[ai] = b[bi] bi += 1 ai += 1 retu...
f2a2bffa40c4dcc8ce10719e4c5340d5816b7088
rpryzant/code-doodles
/interview_problems/2018/CRACKING/4.2.py
573
3.6875
4
# in notes class Node: def __init__(self, d): self.data = d self.left = None self.right = None def __str__(self): s = '' s += '%s\t' % str(self.right) s += '%s\n' % self.data s += '%s\t' % str(self.left) return s def bst(a): return __bst(a, ...
41be6634145090b65d36145e71893f9210417e9a
rpryzant/code-doodles
/purely_random/tictactoe.py
1,938
4.03125
4
from random import choice from sys import argv # helper function to quickly generate a game's worth of coordinates def initAvailable(): return [(x, y) for x in range(3) for y in range(3)] # make a move for a player, given the available board spots def makeMove(player, board, available): # if there aren't any ...
082d22d861e91bf1aa94edb238109f7b13b1ca98
cyoungman9/python-challenge
/PyBank/main.py
1,596
3.625
4
import os import csv bank_csv = os.path.join("Resources", "budget_data.csv") # lists for csv file values months = [] profit = 0 profit_change = [] var = list() count = 0 dif_profit = 0 prev_profit = 0 max_profit = 0 min_profit = 999999 max_date = "" min_date = "" with open(bank_csv, 'r') as csvfile: csvreader =...
ae5631c31e682aa2ec25bd4c9cccd337831a355f
rashonmitchell/projeto-algoritmos
/1_introducao/04_max_min_3.py
1,945
3.59375
4
""" Esta implementação em Java acusa o seguinte erro quando a entrada não possui um numero par de elementos: java.lang.ArrayIndexOutOfBoundsException Para contornar um erro semelhante em python, foi necessário utilizar o seguinte artifício: >>> proximo_indice = min(indice + 1, len(elementos) - 1) """ class Ma...
7b6a2a74bf8218bcdbd910b71af73a3486ab1129
Zsantapala/mid-term-work
/other-work/11-8.py
1,835
3.703125
4
# -*- coding:utf-8 -*- class MedalTable: def __init__(self, ct, gd, sl, br): self.country = ct self.golden = gd self.silver = sl self.bronze = br def new_medal(self, place): if place == 1: self.golden += 1 if place == 2: self.silver += 1...
fd79635cf10e22e42b67c252eb45a32810d81650
Zsantapala/mid-term-work
/other-work/11-4new.py
1,052
4.03125
4
class Vehicle: def __init__(self, sp=15.0): print('init a Vehicle') self.speed = sp self.distance = 0 def drive(self, distance): self.distance += distance print('total drive', self.distance) print('time is', distance / self.speed) print() class Bike(Veh...
7e32f563389c4f2ca99d731c91af6bf6ee4570c1
EvgheniiKunitski/learn-homework-2
/1_date_and_time.py
824
4.21875
4
""" Домашнее задание №2 Дата и время 1. Напечатайте в консоль даты: вчера, сегодня, 30 дней назад 2. Превратите строку "01/01/20 12:10:03.234567" в объект datetime """ import datetime def print_days(): dt = datetime.date.today() delta = datetime.timedelta(days=1) calc_date = dt - delta print(f'Вче...
08a9da5049b3cdeafc70eb99f4024612697d58ac
lalit-code/Weather-App-on-PYTHON
/Weather_app.py
4,882
3.75
4
import tkinter as tk from tkinter import * from tkinter import messagebox import requests import pyttsx3 import speech_recognition as sr import pyaudio HEIGHT = 520 WIDTH = 600 #Creating tkinter intercate root = tk.Tk() root.title("Weather APP") # Initialising Speaker speaker = pyttsx3.init() speaker.setProperty(...
101c780d4f259212210dd541747c05a0b78de965
omkar6644/Python-Training
/q1.py
248
3.921875
4
def transpose(x,y): for i in range(len(x)): for j in range(len(x[0])): y[j][i]=x[i][j] for b in y: print(b) def main(): x=[[1,2],[3,4]] y=[[0,0],[0,0]] transpose(x,y) if __name__=='__main__': main()
71b518fc826e30db92f44aefaf3a5d467e61d714
omkar6644/Python-Training
/python_csv_read.py
232
3.734375
4
#import csv module import csv #open a csv file in read mode with open("emp.csv",'r')as f: #call reader method on file r = csv.reader(f) #convert to list data = list(r) print(data) print(type(data))
7be1898ddb91b314f59cc195eb314d88de88cd5a
omkar6644/Python-Training
/dict_to_json.py
167
3.5
4
#import json module import json dict = {"name": "omkar", "lname": "patil"} #dumps converts dictionary to json string json_st = json.dumps(dict) print(json_st)
ccac62bd50820f0806dc789ba68446bf280e3c3e
omkar6644/Python-Training
/protected_member.py
809
3.84375
4
class Employee: def __init__(self, id , name , designation): #protected data members self._id = id self._name = name self._designation = designation #protected function def _display(self): print(self._id) print(self._designatio...
529b40e8edf7ed3fa1c9ce30a1b133ed32df7beb
adityasinghX/Hackerrank-Code
/10 Days of Statistics/Day 0(1).py
878
4.1875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n = raw_input() elements = raw_input() int_elements = [] # Store elements string into an array where each number is a spot in the array for elem in elements.split(' '): int_elements.append(int(elem)) sum_of_elements = sum(int_e...
9e6e886d7cdb59f202fa976415a1f14cf15a348d
lihongtao1993/TheWar
/监听事件(退出事件).py
1,490
3.546875
4
import pygame from 游戏精灵类 import * pygame.init() game_screen = pygame.display.set_mode(size=(490, 700)) # 1、加载背景图 background = pygame.image.load("./images/background.png") # 2、blit绘制背景图 game_screen.blit(background, (0, 0)) # 3、update更新屏幕 hero = pygame.image.load("./images/me1.png") game_screen.blit(hero, (200, 400)) ...
f2d0bfae72b8c666c3f8876e105563f43113cbe3
BryanQ98/Learning_Python
/ex11.py
318
4.125
4
print "How old are you?", age = raw_input() print "How tall are you?" height = raw_input() print "How much do you weigh?" weight = raw_input() #The above will be filled in by an input, the below will fit that input into a sentence print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight)
deb4d121bc64c5482015ae032c7651d2c9da4daa
18292677162/Python
/python_base/variable_advanced.py
3,078
3.515625
4
# 变量与数据分开储存, 全部采用引用的方式 a = 1 c = 1 print("a " + str(id(a))) print("1 " + str(id(1))) print("c " + str(id(c))) print("1 " + str(id(1))) b = a print("b " + str(id(b))) # 调用函数 及返回值 本质传递的是实参保存 数据的引用 def test(num): print("函数内部 %d 的地址 %d" % (num, id(num))) result = "hello" print("函数内部字符串地址 %d" % id(result)) ...
61ae5fa6311a9e3e06870fee82906d81c5efa60b
18292677162/Python
/python_base/variable_base.py
1,081
4.21875
4
print("hello") print("Hello World") print('AAAAA\nBBBBB') print("""12345 6789 101112""") # this is a test print(1 + 1) print(2 - 1) print(2 * 3) print(10 / 3) print(2 ** 3) print("A" * 10) print(5 // 3) # 变量定义 a = 100 print(a) # 买苹果 price = 8.5 weight = 7.5 money = price * weight print(money) # 变量类型 """ 姓名:小明 年龄:1...
8b51ca71dde88a796255636ee603c4b490070a64
PedroGal1234/Unit3
/perfectNumber.py
249
3.75
4
#Pedro Gallino #9/29/17 #perfectNumber.py - says if a number is perfect num = int(input('Enter a number: ')) i=1 lol = 0 while i < num: if num%i == 0: lol = lol+i i = i+1 if lol == num: print('Perfect') else: print('Not Perfect')
5a4ff1b80ee003bd188d998f6b455e4d2e1f2401
PedroGal1234/Unit3
/loopDemo.py
769
4.25
4
#Pedro Gallino #9/27/17 #loopDemo.py - loops for anf while """ #print I love computer science 5 times for i in range(0,5): print('I love computer science') i = 1 while i <= 5: print('I love computer science') i = i+1 """ """ #print numbers from 1 to 20 for i in range(1,21): print(i) i=1 while i <= 2...
7e943016622ba4fc27ae1a9c2b93edf8b6c444a9
PedroGal1234/Unit3
/warmUp8.py
230
3.65625
4
#Pedro Gallino #10/2/17 #warmUp8.py - find sum of all positive integers less than 100,000 that are divisible by 3, 1o, and 17 sum = 0 for i in range(1,100001): if i%3 == 0 and i%10 == 0 and i%17 == 0: sum = sum+i print(sum)
94ceaba39383bf8b46d8f34ffe4aaec6e11f5e23
RunasDeFrio/ProtocolSimulation
/model.py
10,115
3.5625
4
import math import generators #Класс для работы с величинами, которые могут быть как случайными так и детерминированными. По факту просто контейнер с режимом class RandomValue: def __init__(self, valueStandart, randomGenerator, isRandom): self.value = valueStandart self.generator = randomGenerator ...
3feb7d545cb682599d375afaa907ca566a374f1d
MessiahChen/CS61A
/lab/lab06/lab06.py
440
3.78125
4
def make_adder_inc(n): """ >>> adder1 = make_adder_inc(5) >>> adder2 = make_adder_inc(6) >>> adder1(2) 7 >>> adder1(2) # 5 + 2 + 1 8 >>> adder1(10) # 5 + 10 + 2 17 >>> [adder1(x) for x in [1, 2, 3]] [9, 11, 13] >>> adder2(5) 11 """ "*** YOUR CODE HERE ***" ...
12e736362e1073c95f970dac355ece80fc82cfb4
norahnan/Fluid-flow
/Braid.py
23,396
3.578125
4
#This is an attempt to create a braid class in python based on my previous c++ braid class. I will eventually add extra functionality like braid conjugacy determination. Jan 2017 - Spencer A. Smith #This class will hold the Artin group representation of a Braid. It is able to compare braids (solves the word problem)...
cad982365435fc8e901f68bcc6a746fc63b0f08b
kinalee/holbertonschool-higher_level_programming
/0x07-python-classes/2-square.py
549
4.34375
4
#!/usr/bin/python3 """ 2-square contains class Square that defines a square """ class Square: """ creates an __init__ method with size instance """ def __init__(self, size=0): """ - initializes private instance attribute size - raises errors when size is not int or size is less than 0 ...
1c7062d28823e5bc0817409e053a563d531af99f
kinalee/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/7-update_dictionary.py
219
4.03125
4
#!/usr/bin/python3 def update_dictionary(my_dict, key, value): for i in my_dict.keys(): if i == key: my_dict[i] = value if key not in my_dict: my_dict[key] = value return my_dict
955cf7b4b384795cce1c5c5d54967f977d9b9ad1
kinalee/holbertonschool-higher_level_programming
/0x06-python-test_driven_development/0-add_integer.py
457
4.125
4
#!/usr/bin/python3 """ 0-add_integer Adds 2 integers and returns the sum Contains one module: add_integer """ def add_integer(a, b): """ Both a and b must be integers, a TypeError will be raise otherwise """ if isinstance(a, (int, float)) is not True: raise TypeError("a must be an integer") ...
d04f0d64d70be654a4905ee2db2a64962524e712
kyminbb/multi-armed-bandits
/agents/optimistic_initialization.py
2,605
3.6875
4
from typing import List import numpy as np from . import Agent class OptimisticInitialization(Agent): def __init__(self, bandits: int, arms: int, time_steps: int, initial_values: List[float], q_true: np.numarray) -> None: ...
434595a5c4d6c5dddd48e008b3383487234d79c0
lancyliu/Online-Social-Network-Analysis
/a4/classify.py
4,004
3.59375
4
""" classify.py 1. classify the sentiment of each tweet, pick the top 3 positive and top 1 negative, print these tweets. Using AFINN lexion. save the top 10 positive result and top 10 negative result to classify_result.csv """ from collections import Counter, deque, defaultdict import matplotlib.pyplot as plt import ...
8b41c06c154d01f95883ccfd74906cf1b463dc0c
bohlijo/IEMS_EAU
/exercise_sheet_05/hashFunction.py
6,679
3.5625
4
import random class HashFunction: def __init__(self, prime, universeSize, hashTableSize): self.a = 1 self.b = 0 self.prime = prime self.universeSize = universeSize self.hashTableSize = hashTableSize def apply(self, x): return ((self.a * x + self.b) % self.prim...
d996c812d8838393827608232226e93007b6a533
Naman3vedi-2000/python_fundamentals
/Day3_B45.py.html
2,054
4.59375
5
#!/usr/bin/env python # coding: utf-8 # In[ ]: Introduction to list data types: # In[ ]: Overview: A list is a collection of items in a particular order. Classification: It is classification as an mutable datatype (which we can edit or alter) Declaration of a list ------> [] # In[ ]: # In[7]...
644f4b7cef183459e3966bb618d65042934875e4
vizhka/course
/enter/course1/hw_p2_1.py
513
3.78125
4
# Создать лист из 6 любых чисел. Отсортировать его по возрастанию my_list = [15, 32, 43, 54, 80, 46] my_list.sort() print(my_list) # Make a tuple from 10 random equals number, find max and min t = (2.57, 3.77, 2.11, 4.55, 6.11, 6.87, 4.11, 6.98, 11.54, 18.66) print(max(t)) print(min(t)) # Make a list from 3 words: ['Ea...
d654db222901585ba1f9d9ce3ddf4f97c3024a4e
StephenPrivette/Project-Euler
/Euler Problem 02.py
351
3.890625
4
# even fibonacci numbers fib_sum = 0 next_fib = 0 second_fib = 1 last_fib = 2 while last_fib < 4000000: next_fib = second_fib + last_fib second_fib = last_fib last_fib = next_fib print(last_fib, "lastfib") if last_fib % 2 == 0: fib_sum += last_fib print(fib_sum, "fibsum") ...
e1d07f31391e5143bc9ee549f8ecf9d87b27762a
StephenPrivette/Project-Euler
/Euler Problem 10.py
394
3.609375
4
##The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. ## ##Find the sum of all the primes below two million. number = 5 prime_sums = 5 while number < 1000: prime = True for i in range (2, number // 2 + 1): if number % i == 0: prime = False break if prime ==...
5d36da3ac24ef2b866a4b2403b085588dc10b450
vivekbishwokarma99/Lab_Project
/LabOne/Qn_Seven.py
354
3.5625
4
''' 7. You live 4 miles from university. The bus drives at 25mph but spends 2 minutes at each of the 10 stops on the way. How long will the bus journey take? Alternatively, you could run to university. You jog the first mile at 7mph; then run the next two at15mph; before jogging the last at 7mph again. Will this be q...
8366b1d2b03c77d0c8504b51799d630a3de8f522
vivekbishwokarma99/Lab_Project
/LabFour/Qn_Six.py
102
3.578125
4
''' 6.Write a Python program to count the number of even and odd numbers from a series of numbers. '''
64a4cb34175d562840c5eff12fb7e5f504924e6f
Nirmal1993/Tutorials
/wordfreq.py
229
3.90625
4
def wordfreq(str): wordlist = {} count = 0 for word in str: if word in wordlist: count = count+1 else: wordlist.append(word) wordfreq("hello there good morning there")
b36e307d11abe2c1d61cecbbee33020282303eff
Nirmal1993/Tutorials
/CSVfile.py
153
3.625
4
import csv with open('CSV.csv','r',newline="",encoding='utf-8')as f: file=csv.reader(f) for row in file: print(','.join(row))
5420e51e972b8472bca3932e706e9827fceb3520
maestro089/egor_karpov0022-04
/6.1.py
975
3.609375
4
mass_1 = [] mass_3 = [] def completion_mass_key(): str = [] while(True): check = input() if check == "quit": break else: str.append(check) return str def completion_mass_values(str): str_3 = [] for i in range(len(str)): check ...
2dd5102aa2a9d62b6a839fe786c3bfd537407cb0
wheavin/ProjectEular
/project_euler/012_highly_divisible_triangular_number.py
843
3.5625
4
__author__ = 'William' import itertools flatten_iter = itertools.chain.from_iterable highest_num_factors = 0 def get_triangular_number(divisors): index = 2 triangular_number = 0 while True: triangular_number = sum(range(index)) if len(get_factors(triangular_number)) > diviso...
de326358e23ddf0244fc6c5b9923d4da232fd47a
wheavin/ProjectEular
/project_euler/023_non_abundant_sums.py
2,375
4.1875
4
""" A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it i...
fa6a68f9a34e9de5a6caa300f04d99263275bbb5
YeorgiadouKaterina/Agenda-Maker
/connectToMongo.py
1,055
3.5
4
from pymongo import MongoClient from datetime import date # fill this with your personal username="root" passwrod="rootPass" database="lcThessaloniki" url="""mongodb://{}:{}@127.0.0.1/{}""".format(username,passwrod,database) client=MongoClient(url,authSource="admin")['lcThessaloniki'] data={ 'lc': 'thessaloniki'...
1e44662e8a792962cd9641eec975d4421363e234
luisalcerro/PHSX815_Week12
/python/CentralLimit.py
1,409
3.96875
4
############## This program illustrates the Central limit theorem ########### import numpy as np import matplotlib.pyplot as plt # define a function that samples numbers from a triangular distribution # and takes the mean N times def CentralLimit(N): arr = [] for i in range (0, N): a = np.random.trian...
42d079ca41100051aaabb37d116feb4dcf937a7f
kroze05/Tarea_2
/T2Funciones/6_ejercicio.py
703
4.03125
4
#6) Realiza una función separar() que tome una lista de números enteros y devuelva dos listas ordenadas. La primera con los números pares, y la segunda con los números impares: def separar(*args): lista_pares = [] lista_inpares = [] for i in args: pi=i%2 if pi == 1: lista_pares.a...
327d2274f87153afd7e1d9c8ebcaa86d61e4bab3
JoaoMWatson/ProgAlgoritmo
/projeto criptografia/batalha/grupoDoDavidi.py
780
3.609375
4
from string import ascii_lowercase alfabeto = list(ascii_lowercase) def descriptografador(numero, key): for allP in range(len(numero)): for allA in range(len(alfabeto)): if(alfabeto[allA] == numero[allP]): allA = allA+key if allA < 0: allA =...
cdb9b316d72a913fb920581f5a22409e7e22208f
JoaoMWatson/ProgAlgoritmo
/Testes/descriptografa.py
476
3.828125
4
from string import ascii_lowercase alphabeto = list(ascii_lowercase) sep_um = [] def descriptografar(numeros): for i in numeros: x = numeros.split(i) x = int(i) sep_um.append(alphabeto[x]) for x in sep_um: print(f'{x}', end='') sep_um.remove(x) print(se...
f4e09edaf018ffd08b53598890270006f9c43262
mam446/interview
/testList.py
2,357
3.703125
4
import unittest import random import linkedList class ListTestCase(unittest.TestCase): def setUp(self): self.l = linkedList.singleList() def test_push(self): cur = None last = random.randint(0,100) self.l.push(last) self.assertEqual(self.l.head.data,last,'Initial ...
6c88bc77c6df65f7a5a36455bb57195fdfcfc977
mam446/interview
/linkedList.py
1,475
3.765625
4
class singleNode(object): def __init__(self,data,child=None): self.forward = child self.data = data class singleList(object): def __init__(self): self.head=None self.length = 0 def push(self,data): self.head = singleNode(data,self.head) self.length+=1 ...
a2c26b1daa60fe9db3867fee5df398d8a7459d1a
Sachin-Kumar13/LAB
/odd.py
141
3.625
4
import math; list= list(map(int,input().split(','))) oddNum = [i for i in list if (int(i) % 2 != 0)] for i in oddNum: print(i**2)
11790704007aad60cfa0068f5c7c0d3efe6ef33f
rossdavidson47/RICE-Python-Challenge
/PyBank/PyBank_using_dicts.py
2,550
3.796875
4
# This code should be used for the PyBank homework for the Rice Bootcamp, May 2020. # Requires a set of financial data called budget_data.csv in the Resources sub folder. # The dataset should compose of two columns, Date and Profit/Losses. # Uses dictionaries. #1 Import modules #2 Create Lists to hold the data. #3 Fin...
11ccd634043bc383a7143b294e35cb7ccec21bb3
Kade23/snbank
/bankapp.py
2,150
3.828125
4
import random import os user_input = input("Would you Like to Log In or Close App?: ") print("Please Log in") while user_input == "Log in" : username = str(input("Enter your Username: ")) userpassword = str(input("Enter your Password: ")) file = open("staff.txt", "r") for row in file: field = ...
e5641a9751bcee87fbd4e06a3ef8174290f3a1b3
Aragon-Diego/calidad
/p5/p5.py
2,676
4
4
""" Numero de programa:05 Nombre:Diego Alonso Aragón Villarreal Matricula:361349 Fecha ultima de modificación:30/03/2020 Razón de modificación:Creacion """ """ Clases: Integrar gama F sumaImpar sumaPar P chacarPs """ import math import sys class Integrar: x=0 ...
d37ad246d7e3250bdde474092e4b6d6a84bbb96f
diacarcor/rock-paper-scissors-start
/main.py
1,214
4.25
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) -...
ceee66e9c10e82e81dd7d46e54d4e79c3d7ab8cb
sasa33k/PSCourse
/_01_PyBasics.py
4,173
3.640625
4
""" REPL : read evaluate print & loop Strong type system: there is no implicit type conversion (except bool) Dynamic type system: object types are only resolved at runtime Scopes: contexts in which named references can be looked up Local (current function), enclosing, Global (top-level), Built-in Python named scopes...
77677e579cb838946133497d08e2ed61e028a31e
sasa33k/PSCourse
/_03_PyOOclasses.py
1,752
4.21875
4
# Class - logical group of functions (method) & data *readable & maintainable *special methods only available in class e.g. constructor method students = [] class Student: def __init__(self, name, student_id=0): student = {"name": name, "student_id": student_id} students.append(student) def ...
86e484b1cc28481470fef69138b302395084f17c
trankuong/analysis
/stockParseCSV.py
2,807
3.734375
4
# Authors: Anand Jetha, Dylan Delaney, Kuong Tran, Rachel Cheng # uniqnames: ajetha dylmdel kuong racheng # Date: December 16, 2014 # Purpose: This file is used to parse the CSV data file # Description: Defines functions to break the data up and collect # desired information. import sys ''' Converts a list...
703ab4a7ec396753531e7bb534c7405b64ca7eeb
realhere/Python-Practice
/homework/W1-HomeWork.py
275
3.671875
4
n1=int(input("Enter a Number:")) n2=int(input("Enter a Number:")) n3=int(input("Enter a Number:")) n4=int(input("Enter a Number:")) n5=int(input("Enter a Number:")) list1=[n1,n2,n3,n4,n5] data=n1+n2+n3+n4+n5 print("總和:%d" %(data)) print("最大值:%d" %(max(list1)))
51a74d56b6b67e4c51c7a7b24ae00667aa9867d7
fortunely/LeetCode
/9_PalindromeNumber.py
565
3.84375
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ x_origin = x if x < 0: return False elif x == 0: return True else: reverse_num = 0 while 0 != x: num = ...
7e18b9bbce4610caff41990199e708ae67e3ca14
Emceelamb/nime
/Centralize/ServoMotor.py
628
3.5
4
#!/usr/bin/env python3 from gpiozero import Servo servo = Servo(21) servoPosition = "low" class ServoMotor(object): def __init__(self, pin): servo = Servo(pin) # print("Servo is on pin " + str(pin)) self.position = position def sweep(self): if self.position == "low": ...
13c0f08432d42736e61b12d7af745c875f45572b
patsonev/Python_OOP
/4_1_point.py
433
3.984375
4
from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y def set_x(self, new_x): self.x = new_x def set_y(self, new_y): self.y = new_y def distance(self, other_x, other_y): dist = sqrt((self.x - other_x) ** 2 + (self...
9d254189bc558ae58d903c44dfb63bf9798d585a
LoveYang/Leetcode_BY-
/433. Minimum Genetic Mutation/solution.py
1,631
3.59375
4
# -*- coding: utf-8 -*- class Solution(object): def minMutation(self, start, end, bank): """ :type start: str :type end: str :type bank: List[str] :rtype: int """ lenbank=len(bank) if start in bank: bank.remove(start) count=self.c...
9b4b9fe834e13199763c702a7a766bbf725e2b59
cesarm9/PythonExercises
/minutes_to_seconds.py
258
3.9375
4
minutes = int(input("Type the minutes: " )) secondsinaminute = 60 def minutestoseconds(minutes, secondsinaminute): result = minutes*secondsinaminute return result print(f'there are {minutestoseconds(minutes,secondsinaminute)} seconds in {minutes}')
3a0f187508f42707d4cdc07dfbfb06345965a856
AyushVa27/AI
/stockselling.py
605
3.90625
4
def stockBuySell(price, n): if (n == 1): return i = 0 while (i < (n - 1)): while ((i < (n - 1)) and (price[i + 1] <= price[i])): i += 1 if (i == n - 1): break buy = i i += 1 while ((i < n) and (price[i] >= price[i - 1])): i += 1 ...
fab9b19beff3b92e934d7a4a8c8dcafb84e2f6ba
rakibhhridoy/Google-Certification
/PythonOS/rearrange_test.py
643
3.71875
4
#!/usr/bin/env python from rearrange import rearrange_name import unittest class TestRearrange(unittest.TestCase): def test_basic(self): testcase = 'lovelace, Ada' expected = 'Ada lovelace' self.assertEqual(rearrange_name(testcase), expected) def test_empty(self): testcase = '' expected = '' self.a...
408bc37983334b3e5f576f764f21ec4873ed816d
HSx3/TIL
/algorithm/day01/day1_answer/1. List1/BubbleSort.py
246
3.875
4
def BubbleSort(a): for i in range(len(a)-1, 0, -1): # 범위의 끝 위치 for j in range(0, i): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] #swap data = [55, 7, 78, 12, 42] BubbleSort(data) print(data)
ee122764ca91dc9f2453b715f1449d09fe781c1d
HSx3/TIL
/algorithm/day08/괄호검사.py
975
3.625
4
def checkparen(data): paren = [] for i in data: if i == '(' or i == ')' or i == '{' or i == '}': paren.append(i) if len(paren) % 2 != 0: return 0 if paren[0] == '(' and paren[-1] == ')': for i in range(len(paren) - 1): if paren[i] == '(' and paren[i + 1]...
3aa41d4124f8b9adb2c51cc99fbdd095e4539361
HSx3/TIL
/algorithm/day09/day9-A/순열_재귀.py
315
3.765625
4
def PrintArr(n): for i in range(n): print(arr[i], end= " ") print() def perm(n, k): if k == n: PrintArr(n) else: for i in range(k, n): arr[k], arr[i] = arr[i], arr[k] perm(n, k+1) arr[k], arr[i] = arr[i], arr[k] arr = [1,2,3] perm(3, 0)
f33c81e99e3555a28e5a89101688264c2f662441
HSx3/TIL
/algorithm/day09/day9-A/연습1.py
400
4
4
def push(item): stack.append(item) def pop(): if len(stack) == 0: print("Stack is Empty!") return else: return stack.pop(-1) str = "2+3*4/5" stack = [] for i in range(len(str)): if str[i] == '+' or str[i] == '-' or str[i] == '*' or str[i] == '/': push(str[i]) else...
8fbee9d87a0562c98033793d49af274896463616
HSx3/TIL
/algorithm/AD/숫자찾기(이진탐색).py
524
3.78125
4
import sys sys.stdin = open("숫자찾기_input.txt") def binarySearch(a, key): start = 0 end = len(a) - 1 while start <= end: middle = (start + end) // 2 if key == a[middle]: #검색성공 return middle+1 elif key < a[middle] : end = middle - 1 else: sta...
aed89739cc994700cf40347a14b5fbb46b451bda
HSx3/TIL
/algorithm/day08/종이붙이기.py
298
3.578125
4
def paper(n): if n < 2: return 1 else: return paper(n-1) + 2*paper(n-2) import sys sys.stdin = open("종이붙이기_input.txt") N = int(input()) for test_case in range(N): data = int(input()) n = int(data/10) # print(n) print(f'#{test_case+1} {paper(n)}')
6a068e4e9aaec24e5bd1905ad9639661708a35b9
HSx3/TIL
/startcamp/181217/ex_1.py
181
3.9375
4
# 1 # 다음 리스트의 요소들을 한 줄로 출력하시오 # numbers = [2, 3, 6, 11, 8] # for 문 사용. numbers = [2, 3, 6, 11, 8] for i in numbers: print(i, end = " ")
55e0cebff6a52f2fb6259d83bb4956d8f7253a1b
ennsharma/coding-challenges
/HackerRank/Pythonist 2/maximize_it.py
629
3.703125
4
""" Problem Statement: You are given a function f(X)=X^2. You are also given K lists. The ith list consists of N_i elements. You have to pick exactly one element from each list such that S=(f(X1)+f(X2)+...+f(Xk))%M is maximized. Xi denotes the element picked from the ith list. Find the maximized value Smax thus ob...
ba2d1d0bef21f10dae10886339979a6674e7e1e3
priya6971/Other-Competitive-Programming-Problems
/Count_Of_Number_Of_BSTs.py
615
4.0625
4
## Method Definition ## Concept - Number of Binary Search Tree for given n is equal to Catalan Number ## Catalan Number Series - C_n = summation(C_i-1 * C_n-i) ## Time Complexity - O(N * N!) def uniqueNumberBST(n): n1, n2, sum = 0, 0, 0 if n == 0 or n == 1: return 1 for i in range(1,...
5482d12e3e4d2f22de1fbcf1387e8078bebb8d0c
Senpat/SPARC2019
/TechnicalQuestion/simulation2graph.py
2,564
3.515625
4
#based off of simulation2.py #graphs data #supports up to 1 command line argument (the constant value for determining if a suboptimal gas station is worth investigating) import random import numpy as np import time from math import log import sys import matplotlib.pyplot as plt #default constant is 0.0025 EXPC = 0.0...
d1f79af87d78d5b297b1a7282022beaafe61d7b6
NguyenDuyCuong/Learning
/Python/myInheritance.py
1,387
4.375
4
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() class Student(Person): pa...
10b13361016d45651f69454198da1bd9edeaf417
NguyenDuyCuong/Learning
/Python/mydiction.py
1,240
4.4375
4
# A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) x = thisdict["model"] x = "asd" print(thisdict) x = thisdict.get...
d81dbb4a582f8b9b4c47b90ef79fe4de68f115f0
NguyenDuyCuong/Learning
/Python/myfunc.py
1,063
4.40625
4
def my_function(country="Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1="Emil", child2="Tobias", child3="Linus") # If you do not kno...
dea83a704b63ad6a627e10d4dc6d85939e95e6b7
iamdanielchino/wejapa20wave1
/lab1of1.py
231
4.0625
4
#Quiz: Average Electricity Bill #It's time to try a calculation in Python! # Write an expression that calculates the average of 23, 32 and 64 # Place the expression in this print statement average = (23+32+64)/3 print(average)
71d939e427688ec1017b83bdc3652fec909d2477
ColdHumour/ProjectEulerToolkit
/formula.py
11,501
3.890625
4
# -*- coding: utf-8 -*- """ formula.py Functions implementing formulas via fast algorithms. Function list: sqrt, is_square, isqrt, iroot, gcd, ggcd, extended_gcd, lcm, llcm, sum_floor, generate_integer_quotients, legendre_symbol, padic, max_subarray, mex, pythag_triple_tree co_prime_t...
38f326472e6eb68e913a9c5abd8855453d68168c
ColdHumour/ProjectEulerToolkit
/linalg.py
11,993
3.765625
4
# -*- coding: utf-8 -*- """ linalg.py Functions implementing maths in linear algebra. Function list: dot_mod dot_mod_as_list mat_pow_mod mat_pow_mod_as_list mat_pow_sum_mod gauss_jordan_elimination gauss_jordan_modular_elimination gauss_jordan_modular_elimination_as_list gauss_jord...
bf80efdcf57f2edbf14094aca8ace498a047ae8b
deepakorantak/Python
/Datacamp/DataAnalyst/Course9 - Panda DataFrame merging/panda_load_files.py
1,023
4.3125
4
# Import pandas import pandas as pd # Read 'Bronze.csv' into a DataFrame: bronze bronze = pd.read_csv('Bronze.csv') # Read 'Silver.csv' into a DataFrame: silver silver = pd.read_csv('Silver.csv') # Read 'Gold.csv' into a DataFrame: gold gold = pd.read_csv('Gold.csv') # Print the first five rows of gold print(gold.h...
aa18ecce0cd24fd9f95bc075bf1b1f9d7bf4b384
deepakorantak/Python
/Datacamp/DataAnalyst/Course8 - Panda Data manipulation/panda_groupby.py
2,189
3.71875
4
import pandas as pd # Group titanic by 'pclass' by_class = titanic.groupby('pclass') # Aggregate 'survived' column of by_class by count count_by_class = by_class['survived'].count() # Print count_by_class print(count_by_class) # Group titanic by 'embarked' and 'pclass' by_mult = titanic.groupby(['embarked','pclass']...
633504fc80c4d1936d4a64f82911a88a951a60b1
deepakorantak/Python
/HackerRank/Sets/Python Set Add.py
187
3.578125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT N = int(input()) res = set() if N > 0 and N < 1000: for i in range(N): res.add(input()) print(len(res))
de8c3c9269e182f518bd94878af0c6284cb9fc4a
deepakorantak/Python
/HackerRank/Strings/Python Find a String.py
679
4.03125
4
def count_substring(string, sub_string): found = True start = 0 count = 0 end = len(string) while found: start = string.find(sub_string,start,end) if start != -1: count += 1 start += 1 found = True else: found = False retu...
1b102ec074f259629fcc32531d32d97e436eb0ec
deepakorantak/Python
/Datacamp/DataAnalyst/Course7 - Panda Fundamentals/panda_visualization.py
4,192
3.6875
4
import pandas as pd import matplotlib.pyplot as plt # Create a plot with color='red' df.plot(color = 'red') # Add a title plt.title('Temperature in Austin') # Specify the x-axis label plt.xlabel('Hours since midnight August 1, 2010') # Specify the y-axis label plt.ylabel('Temperature (degrees F)') # Display the plot p...
bd81e9e5949e1094b9556dfda55466ce3d1003e0
deepakorantak/Python
/Datacamp/DataAnalyst/Course7 - Panda Fundamentals/panda_dataframe.py
1,745
3.671875
4
# Import numpy import numpy as np # Create array of DataFrame values: np_vals np_vals = df.values # Create new array of base 10 logarithm values: np_vals_log10 np_vals_log10 = np.log10(np_vals) # Create array of new DataFrame by passing df to np.log10(): df_log10 df_log10 = np.log10(df) # Print original and new data c...
ed54f922abec04347102e157e9cb33939728cf2a
deepakorantak/Python
/Pluralsight/Python Getting Started/class_example.py
2,346
3.71875
4
class ShoppingCart: def __init__(self): self._list = dict() def add_cart(self,order): if (order.item in self._list): self._list[order.item] += order.qty else: self._list[order.item] = order.qty return (True,"Order processed") def delete_cart(self,ord...