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
1e8abbfd8016f6744511e11acc2843c49007e2df
eternalseptember/CtCI
/05_bit_manipulation/07_pairwise_swap/pairwise_swap_sol.py
266
3.796875
4
# Solution def pairwise_swap(num): # Mask odd bits with 0b101010... # Then shift them right by 1 to put them in even spots. # >>> is zero-fill right shift odd_mask = (num & 0xaaaaaaaa) >> 1 even_mask = (num & 0x55555555) << 1 return odd_mask | even_mask
35825b1e001c325e9a96b20b6b2c7bc5a7efa0ce
eternalseptember/CtCI
/02_linked_lists/1_remove_dups/remove_dups.py
1,573
3.8125
4
""" Write code to remove duplicates from an unsorted linked list. How would you solve this problem if a temporary buffer is not allowed? """ class Node: # def __init__(self, data=None, prev=None, next_node=None): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node def print_l...
93adb0fe0405de21c038c3f39502a708a1fd5260
eternalseptember/CtCI
/01_arrays_and_strings/1_is_unique/is_unique_tb.py
192
3.515625
4
# Test case for "is unique" problem. from is_unique import * # True, True, False test_str = ['cat', 'dog', 'squirrel'] for current_str in test_str: print(check_characters(current_str))
23d9d52eb21bda99b493598dfa5f79e0d3a6cf1d
eternalseptember/CtCI
/07_object-oriented_design/08_othello/o_flip.py
2,395
4
4
# Function for flipping pieces. # Meant to be imported into the main Othello class. def flip_pieces(self, row, col, color_placed): check_W = True check_E = True check_N = True check_S = True # Check when piece is placed on edge or corners. if row <= 0: check_N = False elif row >= 7: check_S = False if c...
fb425c9f560215ed98bd635b9338c86bd63d00af
eternalseptember/CtCI
/04_trees_and_graphs/06_successor/successor.py
1,808
3.96875
4
""" Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. """ class Node: def __init__(self, data=None, left=None, right=None, prev=None): self.data = data self.left = left self.right = right self...
8a8ba43f4c7320d2e0e122fbee226841e0771ef3
eternalseptember/CtCI
/05_bit_manipulation/06_conversion/conversion_tb.py
1,001
3.5625
4
# from conversion import * from conversion_sol import * # Test case 1 # Expected result: 2 int_a = 29 # 11101 int_b = 15 # 01111 result = number_of_bits_to_flip(int_a, int_b) print(result) # Test case 2 # Expected result = 0 int_a = 0 # 0 int_b = 0 # 0 result = number_of_bits_to_flip(int_a, int_b) print(result)...
6fc8d2e082b1b309e438b22ed08f95f29d9e381f
eternalseptember/CtCI
/04_trees_and_graphs/12_paths_with_sum/paths_with_sum_sol_1.py
1,274
3.609375
4
# Solution 1: Brute Force # In a balanced tree, runtime is O(N log N). # In an unbalanced tree, O(N^2). class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def __str__(self): left = None right = None if self.left is not None: left =...
a4819f14fd1f621f38cd62a0e7faf9e099c54214
eternalseptember/CtCI
/04_trees_and_graphs/06_successor/successor_tb.py
5,056
3.59375
4
# Test cases for "successor" problem. # from successor import * from successor_sol import * """ # ************************************************ # ******************** TREE 1 ******************** # ************************************************ node13 = Node(13) node14 = Node(14, node13) node13.prev = node14 n...
97f0ea7b6cf6b446b62f31056f135849da02697d
eternalseptember/CtCI
/04_trees_and_graphs/11_random_node/random_node_sol_2.py
2,283
3.75
4
# Option #7 from random import * class Tree: def __init__(self, root=None): self.root = root # should be a TreeNode. def get_size(self): if self.root is None: return 0 else: return self.root.size def get_random_node(self): if self.root is None: return None random_index = randint(0, self....
7dde7eaebc7bd7d6127e23c28f111f50febbbf13
eternalseptember/CtCI
/04_trees_and_graphs/11_random_node/random_node_sol_test_1.py
901
3.828125
4
# Testing option 6. from random_node_sol_1 import * # Example tree from solutions manual # How does insert function work? # nodes_list = [10, 5, 15, 17, 3, 7, 20, 30] # This is the tree in the example: nodes_list = [20, 10, 30, 5, 3, 7, 15, 17] head = None for val in nodes_list: if head is None: head = Node(...
e666f6a73928248c132a47bf9456d9f7691c7d67
eternalseptember/CtCI
/04_trees_and_graphs/09_bst_sequences/bst_sequences.py
1,282
4.0625
4
""" A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree. """ class Node: def __init__(self, data=None, left=None, right=None): self.data = data ...
940d9218dabb8aeced04b9726daf566781843883
eternalseptember/CtCI
/04_trees_and_graphs/08_first_common_ancestor/first_common_ancestor_sol_4.py
2,649
3.9375
4
""" Implementing the solution for first common ancestor problem. Solution 4: Optimized In solution 3, covers searches all nodes under root for p and q, including the nodes in each subtree (root.left and root.right). Then it picks one of the subtrees and searches all of its nodes. Each subtree is searched over and ove...
bea6d8a0680e3c04423bf50c4e89d162cdace2af
eternalseptember/CtCI
/04_trees_and_graphs/01_route_between_nodes/route_between_nodes.py
1,044
4.1875
4
""" Given a directed graph, design an algorithm to find out whether there is a route between two nodes. """ class Node(): def __init__(self, name=None, routes=None): self.name = name self.routes = [] if routes is not None: for item in routes: self.routes.append(item) def __str__(self): list_of_rou...
9e4ce1100480c37a11a6740af736f4c0ab0510f5
eternalseptember/CtCI
/07_object-oriented_design/11_file_system/file_system_tb_3.py
776
3.640625
4
# Testing basic file and folder size count. from file_system import * dir_1 = Directory("dir_1", None) file_1 = File("file_1", dir_1) file_2 = File("file_2", dir_1) print('New:') print(dir_1.get_full_path()) print(file_1.get_full_path()) print(file_2.get_full_path()) print() print('Contents of dir_1:') dir_1.g...
275a53e865259a0d15f82cdacdc2a58a641b9343
eternalseptember/CtCI
/07_object-oriented_design/11_file_system/file_system.py
2,226
4.28125
4
""" Explain the data structures and algorithms that you would use to design an in-memory file system. Illustrate with an example in code where possible. """ # What is the relationship between files and directories? class Entry(): def __init__(self, name, parent_dir): self.name = name self.parent_dir = parent_di...
e5cf07e7dedfa0f984892e99e3b621b0d14c3ec2
eternalseptember/CtCI
/05_bit_manipulation/03_flip_bit_to_win/flip_bit_to_win.py
1,285
3.90625
4
""" You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of ls you could create. """ def longest_sequence_of_ones(num): if num == -1: return "No bits are flipped." # convert to binary bin_str = bin(num)[2:] # gets the binary string bin_st...
bc0c85fe770ac88a7b7d66239c6bdba5057aecc7
eternalseptember/CtCI
/02_linked_lists/4_partition/partition_tb.py
409
4.03125
4
# Test cases for the "partition" problem. from partition import * # Expected result: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 x = 5 values = [3, 5, 8, 5, 10, 2, 1] head = None for value in values: head = add(head, value) print('linked list adding all nodes:') print_linked_list(head) print() print('linked list after pa...
beea3d72fe460cd89d9d6ebe428950f258e56324
aaronPTB/simple-neural-net
/identify.py
3,874
3.671875
4
import numpy as np class NeuralNetwork: """Neural network class that allows for simple foreward and backward propogation with a momentum-based stochastic gradient descent method. Has a dependency on numpy""" def __init__(self, input_size, hidden_size, output_size, learn_rate = .1, re...
005103cb3b2736711e6dd9a194a19cb0db8bd420
jcs-lambda/cs-module-project-algorithms
/sliding_window_max/sliding_window_max.py
1,016
4.34375
4
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): # initialize first window and max window = nums[:k] current_max = max(window) maxes = [current_max] # slide window for x in nums...
c5db799bc3a11b3ca4faf7f703950f04f9dd9d43
ninaalli/AdultingRPG
/AdultingSeed.py
691
3.53125
4
""" Seed the database with admins """ import sqlite3 db = 'adulting.db' PLAYERS = [ ["hrgunn", "FourHead", "male", "single", "28", "Athlete"], ["ninaalli", "EleGiggle", "female", "significantother", "33", "Hacker"] ] conn = sqlite3.connect(db) c = conn.cursor() print("Destroying old data") c.execute("D...
b655006b541cc4123c0ee1553d9df9596ed30d02
gaoshanxiaoao/Python-Code
/python_pratice_codes/test3.py
450
3.890625
4
magicians = ['alice', 'david', 'carolina'] count = 0 for magician in magicians: print(magician) count = count + 1 print('\n') print(count) for value in range(1, 10): print(value) numbers = list(range(2, 11, 4)) print(numbers) squares = [] for value1 in range(1, 11): square = value1**2 squares...
78395439d8cd16fa87b591b91f4533b3634c43ae
jjwarren44/nnfs
/softmax.py
1,743
4.0625
4
import math import numpy as np layer_outputs = [4.8, 1.21, 2.385] class Activation_Softmax: def forward(self, inputs): # Get unnormalized probabilities exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True)) # Normalize for each sample/obs probabilities = ex...
eb3fafe0f626a885076cc7ee791ad8b31cc69cac
jjwarren44/nnfs
/activation_functions.py
1,891
3.703125
4
import numpy as np # example data import nnfs from nnfs.datasets import spiral_data nnfs.init() # Dense layer class class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.10 * np.random.randn(n_inputs, n_neurons) # * 0.10 to get values between -1 and 1 self.biase...
c7e841bf7cec7f8272f3287dd9bba9688bdf89b6
pypower-codes/Email_with_GUI
/gmail.py
4,886
3.6875
4
import smtplib from tkinter import * import tkinter.messagebox from PIL import ImageTk, Image import wget import cv2 def send_email(SUBJECT, MESSAGE): try: tkinter.messagebox.showinfo("Message","Email sending process initiated.") server = smtplib.SMTP('smtp.gmail.com:587') se...
808f45c708658564984a6e222659c16cdd996594
DimitarYordanov17/CodeWarsChallenges
/Problems/HumanReadebkeFormat.py
1,618
3.90625
4
def format_duration(seconds): minutes = seconds // 60 hours = minutes // 60 days = hours // 24 years = days // 365 elements = {} elements["seconds"] = seconds % 60 elements["minutes"] = minutes elements["hours"] = hours elements["days"] = days elements["years"] = years el...
ff2b42fa02e8621053ca89b427af46922685d1d1
chaimakr/Task-manager
/database.py
918
3.609375
4
import sqlite3 import os def create_db(database_filename): connection = sqlite3.connect(database_filename) cur = connection.cursor() cur.execute("DROP TABLE IF EXISTS Task") cur.execute("DROP TABLE IF EXISTS User") cur.execute( "CREATE TABLE Task (ID INTEGER PRIMARY KEY, CONTENT TEXT NOT NU...
0eac9fc85b6ba1d1b4e203402267cce2782f7f8c
lelkok228/python_homework
/main.py
5,317
3.5625
4
import json import sys import argparse def read_string(input_file): input_string = '' if input_file: with open(input_file, 'r') as in_: input_string = in_.read() else: for line in sys.stdin: input_string += line return input_string def write_string(output_stri...
4b4d334cf3b357c943d83b523bb1b7e4fb18a62c
DAGG3R09/coriolis_training
/assignments/Q38_average_words.py
347
3.734375
4
def average_words(filename): word_count = 0 word_length_count = 0 for line in open(filename, "r"): words = line.strip().split() word_length_count += sum(map(len, words)) word_count += len(words) return word_length_count/word_count if __name__ == "__main__": print(averag...
9a40b9d9bee4f82ba28a3f9d2124440df6cf9ab7
DAGG3R09/coriolis_training
/assignments/Q10_overlapping.py
318
4.125
4
def is_overlapping (l1, l2): for le1 in l1: for le2 in l2: if le1 == le2: return True return False if __name__ == "__main__": l1 = [1, 2, 3, 4, 5] l2 = [5, 6, 7, 8, 9] l3 = [6, 7, 8, 9, 10] print(is_overlapping(l1, l2)) print(is_overlapping(l1, l3))
e2e749710a1f444020cf761f8645e1ffc988244e
DAGG3R09/coriolis_training
/assignments/Q39_guess_number.py
578
4.0625
4
from random import randint def start_game(): name = input("Enter Name: ") print ("Well, " + name + ", I am thinking of a number between 1 and 20.") guess_count = 0 number = randint(1, 20) while True: guess = int(input("Take a guess: ")) guess_count += 1 if guess == number...
192f6c5de81a9061518b89c549edef82cd94000c
DAGG3R09/coriolis_training
/assignments/Q5_translate.py
323
3.59375
4
from Q4_vowel import is_vowel def translate(string): result = "" for s in string: if is_vowel(s) or s == ' ': result += s else: result += s + "o" + s return result if __name__ == "__main__": print(translate("this is fun")) print("tothohisos isos fofunon")...
cbd045da276abc05265ab08f21352eb23b31802f
DAGG3R09/coriolis_training
/assignments/Q24_singular_form.py
536
3.65625
4
def check_endings(verb): ending = ["o", "ch", "s", "sh", "x", "z"] for e in ending: if verb.endswith(e): return True return False def get_singular_form(verb): if verb.endswith("y"): verb = verb.replace("y", "ies") elif check_endings(verb): verb += "es" e...
cb6b08d30acb122fb1bc47e2d73c7d04b872d16c
loyalchicken/minesweeper.ai
/server/solver/logic/board_helpers.py
2,400
4.0625
4
################################## GENERATING BOARD LOGIC ##################################################### import numpy as np def generateMines(num_rows, num_cols, num_mines): """Generates a list of numbers corresponding to the 1D coordinates of the squares that are mines. O(n) time, where n = num_rows*nu...
ccc3d0af9a02b5280126244fb2d312bfec631365
unwosu/ThinkDeep
/trainer/Config.py
1,862
3.609375
4
from collections import namedtuple # Values for the input and the output layers # @type: The input or output layers datatype # @shape: This is the shape of the input or the output layer. # @cls: The output layer size: represents a single integer. Value = namedtuple("Value", ["type", "shape", "cls"]) # Used to get th...
eda5d72ab7b6c0815fe0fdddbd18b0ae01e9ca01
unwosu/ThinkDeep
/dataset/ConvMNIST.py
624
3.515625
4
import tensorflow as tf from dataset.Dataset import Dataset, DataValues from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data") class ConvMNIST(Dataset): """ MNIST DATASET """ def __init__(self, batch_size): Dataset.__init__(self, batch_size) in_resh...
0ee69a0517459b2fd30c19b544a80a6771dbedb4
simsekfurkan/python_temel
/reverse.py
289
4.09375
4
data = [[1, 2], [3, 4], [5, 6, 7]] flat_list = [] def flatten_list(data): for element in data: if element.sort(reverse = True): flatten_list(element) else: flat_list.append(element) flatten_list(data) flat_list.reverse() print(flat_list)
cbbf13156b8fa6f000ea4d3d8f67c301df9ec0af
kali237/deep-learning-2019
/board_encoder.py
1,544
3.5625
4
import numpy as np from board import TicTacToe def encode_board(board, player): board_st = board player = player board_enc = np.zeros([3, 3, 3]).astype(int) for i in range(3): for j in range(3): if board_st[i, j] != ' ': if board_st[i, j] == 'X': ...
c4747ba8dfb9374ff0a4b9c8fa683d6ee59fb299
Yuandjom/Automate-the-Boring-stuff-with-Python
/Chapter 6 Manipulating Strings.py/TablePrinter.py
350
3.53125
4
tableData = [['apple','oranges','cherries','banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs','cats','moose','goose'] ] def printTable(datafromtable): colwidth = [0]*len(tableData) print(colwidth) for listfound in datafromtable: for items in listfound : print...
f01f3cb9fdf5bd6c4167da2ff209ec7df0308681
subashchandarA/Python-Lab-Pgms-GE8151-
/11MostFrequentWord.py
660
4.34375
4
#Most Frequent word in a string #str="is program is to find the of the word in the string" filename=input("Enter the file name to find the most frequent word: ") fo=open(filename,'r') str=fo.read() print("The given string is :",str) wordlist = str.split(" ") d={} for s in wordlist: if( s in d.keys(...
5dac50e3ef0821386d271fe18a353c279e69ea1e
subashchandarA/Python-Lab-Pgms-GE8151-
/6.1 selecion sort(python method).py
1,356
4.21875
4
def selectionsort(lt): "select the min value and insert into its position" for i in range(len(lt)-1): #min_pos=x #for x in range(i+1,len(lt)): # if(lt[min_pos]>lt[x]): # min_pos=x min_pos=lt[i:].index(min(lt[i:])) # FIND THE INDEX OF M...
773762755424c84ef55b4218da57e14bfcdaf07a
kevinpalacio/AprendiendoPython
/Aleatorio.py.py
1,010
4.21875
4
# Autor : Kevin Oswaldo Palacios Jimenez # Fecha de creacion: 16/09/19 # Python tendra varios modulos(module), estos modulos son # librerias que tiene python # Se necesita in modulo para un programa, # import, es la primera instruccion que debera estan presente # en la consola import random # Definimo...
5a00874694eb114f47cfa9d9b7a04b4726d7694b
StBinando/w2d2-homework_testing
/testing_start_code/tests/calculator_test.py
492
3.546875
4
import unittest from src.calculator import add, divide, multiply, subtract class TestCalculator(unittest.TestCase): def test_add__returns_10(self): self.assertEqual(10, add(3, 7)) def test_subtract__returns_negative_4(self): self.assertEqual(-4, subtract(3, 7)) def test_divide__returns_fl...
7b563db813ba6098e28508bdf66c0242a8295577
RobotTurtles/mid-level-routines
/Apps/Basics.py
958
3.546875
4
from Movement import Movement class Basics(object): def __init__(self, movement, logger): self.m = movement self.logger = logger self.logger.info("Initialized Basics") def execute(self, option): turnAmount = 180 driveAmount = 50 option = option.lower() ...
c044e974184c3872e0fb62c8cc9c8dd079369016
stormpython/brewmaster
/brewmaster/__init__.py
1,283
3.8125
4
# Main Algorithm for Brew Master # # INPUT # 1. Accepts a search term as input, which is either a beer or brand name. # # GET BEER AND IT'S ATTRIBUTES # 2. The search term is looked up in the beer database. # 3. If the beer is found in the database, a dict of beer attributes is # returned. # 4. Else, an API call is ...
a7cd794a1ef6fc543980181f1cf7144b6dd6639f
ShreyaPriyanil/Sorting-in-Python
/insertionsort.py
514
4.21875
4
def insertionSort(alist): for index in range(1,len(alist)): print("TRAVERSAL #: ",index) position = index while position>0 and alist[position-1]>alist[position]: temp = alist[position] alist[position] = alist[position-1] alist[position-1] = temp ...
00c79cd15aa486a5d055d21c7ab18a9a3f7dc65e
ysig/ece_projects
/advanced-pl/7/user-script/pl2_7_play.py
3,547
3.65625
4
#!/usr/bin/env python import requests import re import sys from math import sqrt #def play(number): # moves = ( # "!.,",#0 # ":.", #1 # "::+.",#2 # ":::++.",#3 # "::+:+.",#4 # ":::+:++.",#5 # ":::++:+.",#6 # "::::++:++.",#7 # "::+:+:+.",#8 # ":::++::++."#9 # ) # befunge = "!" # digits = map(int,l...
7be358856ddbfcd05bf810b2a1ec766ecd72b68a
wolf1347/The-Tech-Academy-Basic-Python-Projects
/misc practice files/Nice Or Mean_tutorial.py
3,833
4.15625
4
# # Python: 3.8 # # Author: Amber J. Wolf # # Purpose: The Tech Academy - Python Course, creating our first program together. # Demonstrating how to pass variables from function to function # while producing a functional game. # # Remember, function_name(variable) _means we pass in the variab...
891dfbda081a38932666f0499fd6a61ee2afd0ae
QNovak/PythonSorter
/Sorting.py
370
3.96875
4
numbers = [67,45,2,13,1,998] output = [] while numbers: smallest = min(numbers) index = numbers.index(smallest) output.append(numbers.pop(index)) print(output) numbers_2 = [89,23,33,45,10,12,45,45,45] output = [] while numbers_2: smallest = min(numbers_2) index = numbers_2.index(smallest) ou...
707e3441f9f269b80e62822e03464c5e093f915e
aponte411/algorithms-python
/graphs/search_maze.py
1,143
3.96875
4
from collections import namedtuple from typing import List # WHITE = unvisited # BLACK = visited WHITE, BLACK = 0, 1 Coordinate = namedtuple('Coordinate', ('x', 'y')) def search_maze(maze: List[List[int]], start: Coordinate, end: Coordinate) -> List[Coordinate]: def backtracking(coordinate: Coordinate) -> bool: ...
56114c3b423c6f246731b3252bf8f466f795dadf
aponte411/algorithms-python
/recursion/phone_letter_combinations.py
786
3.765625
4
from typing import List, Tuple DIGIT_MAPPING: Tuple[str] = ('0', '1', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz') def letter_combinations(digits: str) -> List[str]: def dfs(digit_index, partial_combination): if digit_index == len(digits): result.append(''.join(partial_combination...
9313306af81980f9c108dc3ee73ee6ca2076e175
aponte411/algorithms-python
/strings/min_steps_to_make_anagram.py
783
3.59375
4
import pytest from collections import defaultdict def min_steps(s: str, t: str) -> int: # count the number of chars of s # and then walk through t, if we have seen that # number before decrement it, # else increment the 'steps' pointer # which holds the number of steps we'd need to # take a st...
1295c95b6155121373e29070c78e22568cc22c81
aponte411/algorithms-python
/primitive_types/count_bits.py
301
3.875
4
def count_bits(n: int) -> int: num_bits = 0 mask = 1 for _ in range(32): if n & mask != 0: num_bits += 1 mask <<= 1 return num_bits def test(): n = 12 expected = 2 result = count_bits(n) print(result) if __name__ == "__main__": test()
c2203fd16a972c80f7e86e9578f094709880f46b
aponte411/algorithms-python
/sorting/count_sort.py
811
3.921875
4
from typing import List def sort_scores(scores: List[int], max_score: int) -> List[int]: result = [] counts = [0 for _ in range(max_score + 1)] for num in scores: counts[num] += 1 # walk backwards and add scores in descending order # forward for ascending count_idx = len(counts) - 1 ...
a2024a792512161e2001f4da50e4c2742d9d8c46
aponte411/algorithms-python
/recursion/permutations.py
879
3.9375
4
from typing import List def permutations(A: List[int]) -> List[List[int]]: """ O(n * n!) time, O(n *n!) space """ def dfs(index): if index == len(A) - 1: # make a shallow copy result.append(A.copy()) return for next_index in range(index, len(A)): ...
38e7ead614659577d7f51c4d119fc815d1d49673
aponte411/algorithms-python
/strings/check_perm_inclusion.py
820
3.71875
4
def contains_perm(s1: str, s2: str) -> bool: # Count distribution of characters in constant space s1freq = [0]*26 s2freq = [0]*26 for i in range(len(s1)): s1freq[ ord(s1[i]) - 97 ] += 1 s2freq[ ord(s2[i]) - 97 ] += 1 # if the distributions match, theres a permumation if s1freq =...
9591f21e7b907238ccf357be979dc0a86839a0ad
aponte411/algorithms-python
/recursion/wiggle_max_length_recursive.py
894
3.875
4
from typing import List def wiggle_max_length_recursive(nums: List[int]) -> int: def calculate_max_count(index: int, is_up: bool) -> int: max_count = 0 for next_idx in range(index+1, len(nums)): if (is_up and nums[next_idx] > nums[index]) or (not is_up and nums[next_idx] < nums[index])...
df1eb693316cd623603e43fbee56746b8445b821
shivdazed/Python-Projects-
/Exceptionhandling.py
324
4.15625
4
try: a = int(input("Enter the number A:")) b = int(input("Enter the number B:")) c = a/b print(c) #except Exception as e: # print(e) except ZeroDivisionError: print("We can't divide by zero") except ValueError: print("Your entered value is wrong") finally: print("Sum = ",a+...
cf98191c381f004990782cd7c4a7c0a3e6519471
shivdazed/Python-Projects-
/filehandling.py
366
3.78125
4
file = open(r'C:\Users\anuro\Desktop\student.txt','r') n = input("Enter your name:") std = int(input("\Enter which standard you are in currently:")) std_id = input("\Enter your student ID:") m = [] print("Enter the marks of Five Subjects,Physics Chemistry Maths Biology English:") for i in range(5): r =in...
8b886230b5e8b749480f899bac95868e99d0c48b
shivdazed/Python-Projects-
/Calci.py
553
4.28125
4
print("Enter two numbers into the calci\n") n1 = int(input("Enter the first number---")) n2 = int(input("Enter the second number---")) o = input("Choose operator--\n'+'~Addition \n'-'~Subtraction\n'*'~Multiplication\n'/'~Division\n") if o == '+': print(f"The sum of {n1} and {n2} ={n1+n2}") elif o == '-'...
a232ac2221f789c6657d10dba97bdd280e483c90
patpatforcadela/Python-Data-Structures
/BinaryTree.py
4,644
3.671875
4
from collections import deque class BinarySearchTree: def __init__(self, data): self.right = None self.left = None self.data = data def addChild(self, data): if data == self.data: return if data < self.data: if self.left: ...
4526d419883435c30e14f1a73aa8c3760a0c1aed
Lukematic/Corpus-Methods-Intro
/Course-Materials/pyclass1_notes.py
3,300
4.71875
5
# -*- coding: utf-8 -*- """ This represents the code used in our python class on Day 5 (the first day of programming in Python) Please refer to the Python tutorials for more detailed information """ print("Hello, World") #we can print strings print(1.34564) #we can print numbers (integers and floats) print(1 + 2) # we...
790cacdd70434560e39af633a09f2a22b99f1934
adrezni/vehicle-claims-processing
/TextClassify2.py
3,571
3.734375
4
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from sklearn.preprocessing import LabelEncoder from tensorflow.keras.preprocessing.text import Tokenizer from keras.utils import to_categorical from tensorflow import keras training_portion = .99 # Use 80% of d...
fabebd614635418e78becd731154212edf2b5c9d
sangle-sangle/ssafy-algorithm
/이승열/BOJ_1238_파티.py
834
3.578125
4
from heapq import heappush, heappop def dijkstra(start,s,times): heap = [] times[start] = 0 heappush(heap,[0,start]) while heap: w, n = heappop(heap) if times[n] < w: continue for to, time in s[n]: total = time + w if total < times[to]: ...
0a8f4d934631fa9b895ef2a3af3f1b4adb38bec9
JaimeLynSchatz/project-stash
/UWebDevUnit2/notes for ps2-1/abbrv.py
353
3.640625
4
months_abbvs = dict((m[:3].lower(), m) for m in months) #this nifty little script creates abbreviations for the entries in a dictionary list def valid_month(month): if month: short_month = month[:3].lower() return month_abbvs.get(short_month) "<b>%s</b>" %thestringtosubstitute print sub1("runnin") ...
0042f2d877576f6dd4facc8585eb31cdb06ab8b3
CalvoSeko/StartupPython
/programming challenges/speed tracker.py
115
3.59375
4
time1=float(input("initial time")) time2=float(input()) numberPlate=str(input()) speed=1/(time1-time2) print(speed)
5123db22714fc098cb2080b4dddf434220f84def
Poonam-Singh-Bagh/python-question
/List/bubble_sort_nested_list.py
327
3.9375
4
'''Sorting in nested list''' list = [[3,5,1,6,7],[8,2,9,7,4]] i=0 while i<len(list): j=0 while j<len(list[i]): k=0 while k<len(list[i])-1: if list[i][k] < list[i][k+1]: list[i][k],list[i][k+1]=list[i][k],list[i][k+1] else: list[i][k],list[i][k+1]=list[i][k+1],list[i][k] k=k+1 j=j+1 i=i+1 print...
1908c5221fbde8652d895d1d526ce1930b6041c3
Poonam-Singh-Bagh/python-question
/Dictionary/new_dict.py
342
3.953125
4
'''Q.2 Make a dictionary where all the dictionaries keys and values will be together''' dic1={1:10, 2:20} dic2={3:30,2:40} dic3={5:50,6:60} mix_dict = {} for key, value in dic1.items(): mix_dict[key]=dic1[key] for key, value in dic2.items(): mix_dict[key]=dic2[key] for key, value in dic3.items(): mix_dict[key]=dic3[...
49d6442c6b9f8d9acbfd0678a5df66a822427ffe
Poonam-Singh-Bagh/python-question
/Loop/strong_number.py
294
4.0625
4
'''Q.2 Strong number''' user = input("Enter a number: ") number = list(user) sum = 0 for i in number: num=int(i) f = 1 for i in range(num,0,-1): f=f*i sum=sum+f if int(user) == sum: print(user, "is a Strong number") else: print(user, "is not a Strong number")
b6bc07d1a9c68a828d2e8192f3f6ccdf774797ca
Poonam-Singh-Bagh/python-question
/Loop/factorial.py
100
4.03125
4
''' Q.1 Write a program to print factorial of 5.''' i=5 f=1 while i>1: f=f*i i=i-1 print (f)
5c4e2516c64434bc9d052b79d27d3642eed23f0a
Poonam-Singh-Bagh/python-question
/List/is_alphabet_in_string.py
293
3.90625
4
'''Check whether the alphabet is present in a string.''' user = input("enter a word: ") text1 = "poonam is giving interview" text=list(text1) print(text) i=0 count=0 while i < len(text): if user == text[i]: count=count+1 i=i+1 print (user, "is coming",count, "times")
846389fff517d624189a2058e5e247f0f5467e93
Poonam-Singh-Bagh/python-question
/List/list_datatype_arrangment.py
473
3.953125
4
''' Separate the list by data type wise.''' list = ["poonam", 78.9, 65, "Rabiya", 87, "Rinki", 37.7, 57] str_list = [] int_list = [] float_list = [] for i in range(len(list)): if type(list[i]) == str: str_list.append(list[i]) elif type(list[i]) == int: int_list.append(list[i]) elif type(l...
08e7e22f6f39a02caca937e0fca7982fb33c901c
Poonam-Singh-Bagh/python-question
/Loop/multiplication.py
228
4.21875
4
''' Q.3 Write a program to print Multiplication of two numbers without using multiplication operator.''' i = 1 a = int(input("enter a no.")) b = int(input("enter a no.")) c = 0 while i <= b: c = c + a i = i + 1 print (c)
13cd95427f9fed8977a2b5de25abae5c22d361c6
ONJoseph/Python_exercises
/index game.py
1,013
4.375
4
import random def main(): # 1. Understand how to create a list and add values # A list is an ordered collection of values names = ['Julie', 'Mehran', 'Simba', 'Ayesha'] names.append('Karel') # 2. Understand how to loop over a list # This prints the list to the screen one value at a time fo...
b1b194344a66663254e5df6bf33d173e584a6afa
EMAT31530/ai-group-project-team-football
/football_results.py
1,554
3.515625
4
from math import * import numpy as np import pandas as pd import matplotlib.pyplot as plt def load_points_from_file(filename): points = pd.read_csv(filename, header=None) goals_for = points[9].values goals_against = points[10].values return goals_for, goals_against def goal_difference(goals...
1f0a87994dde4fce0b7cf236c547dcc3ca794442
hellbell/opencv_workshop2017
/win/face_detector.py
588
3.5625
4
import cv2 # Capture the video using USB cam cap = cv2.VideoCapture(0) # Load Face Detector face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') while(True): # Capture frame-by-frame ret, frame = cap.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect faces in the frame ...
b1f2f37df7b5e286db360a9f0a468b3f41f04d08
siayi/python
/basic/datetime-basic.py
832
3.703125
4
import time ticks=time.time() print("No of seconds elapsed:",ticks) print(time.localtime()) print("Localtime:",time.localtime(time.time())) ftime=time.asctime(time.localtime(time.time())) print("Time:",ftime) # calendar for a month import calendar cal=calendar.month(2020,4) print("Calendar".center(50,"*")) pr...
f65b103a1ad22df7fe4a958cbd8ac09708e3f617
jianew/MyPythonScript
/forSPR/werget.py
803
3.703125
4
# !/usr/bin/env python #-*- coding:utf-8 -*- def mini_edit_distance(stringa,stringb,ins_cost,subst_cost,del_cost): n=len(stringa) m=len(stringb) distance=[[0 for i in range(m+1)] for j in range(n+1)] for i in range(1,n+1): distance[i][0]=distance[i-1][0]+ins_cost for j in range(1,m+1): ...
16e1cfe37180beaa968d2d082bcdbbbf98628b6d
GrgDev/AdventOfCode
/2020/06/aoc_2020_06.py
3,201
3.96875
4
import argparse # The parse_args function here generally just parses for two things: input file and puzzle part. # I believe every AOC puzzle comes in two parts and so sometimes requires two code paths. # Sometimes it is easier to implement two different code solutions per part but this gives you # the option of usin...
29b810283246766c589a4d37268a0d01c9807063
vinsmokemau/PythonRandomExercices
/16 Agregar una vez/agregar_una_vez.py
562
3.953125
4
def agregar_una_vez(lista, elemento): try: if elemento not in lista: lista.append(elemento) else: raise ValueError except ValueError: print('Error: Imposible añadir elementos duplicados => {}'.format(elemento)) lista_prueba = [1, 5, "Hola",-2] elemento1 = int(inp...
e79cf68390c122520d10fdd8507eedb729f2bdfc
vinsmokemau/PythonRandomExercices
/13 Calculo Figuras/calculo_figuras.py
4,273
3.65625
4
def perimetro_cuadrado(lado): return lado*4 def perimetro_circulo(diametro): return diametro*3.14 def perimetro_triangulo(lado1, lado2, lado3): return lado1+lado2+lado3 def perimetro_pentagono(lado): return lado*5 def area_cuadrado(lado): return lado*lado def area_circulo(radio): return (radio**2)*3.14 def ...
3b9d8c076fb18d3f083d0854615e00883e7a1f57
okrmartin/reto2
/Tests/BL/EvaluateTests.py
3,376
3.78125
4
import unittest from BL.strategy import Strategy class EvaluateTestCases(unittest.TestCase): def test_WhenEvaluateA_ItShouldBe0(self): """ When the string list is '['A']' the number of pairs should be 0 """ # Arrange string_list = ['A'] expected_value = 0 ...
1d3b1fc83376f9f7a6feca17faac597b8c677c34
jacob-parmer/imdb_scraper
/data_display.py
2,427
3.671875
4
""" ### Author: Jacob Parmer, Auburn University ### ### Last Updated: August 11, 2020 """ import numpy as np import matplotlib.pyplot as plt import random as rnd from IMDb import TVShow class DataDisplay: def __init__(self, data): self.data = data self.arr = [[]] self.fig = None self.ax = None """...
24884032f24eae9d1c2b17b5041fa7de62dbacc9
QGlogichacker/Algorithm
/NumPy_demo/3 ArrayCalculate.py
3,718
3.6875
4
import numpy as np from numpy import * print(''' ####################################### # 用数组表达式代替循环的做法,通常称为矢量化 # ####################################### # 首先是array的情况 # 简单的标量运算 ''') arr = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]], dtype=int) # 创建二维数组 print("# 元素乘arr*arr\n", arr*arr) # 行列号相同的数组元素间运算 pr...
66e32e2f77a1d6b1e6d21c0e74dd5de3993eb817
GuibinHu/shiyanlou-code
/jump7.py
126
3.59375
4
i=1 while i<=100: if i%7==0: pass elif i%10 == 7: pass elif i//10 == 7: i=i+1 continue else print(i) i = i + 1
ca67ed3630bf2bf15468aaacd138312cb1854ad8
shubhamjha25/FunWithPython
/coin_flipping_game/coinflipgame.py
635
4.21875
4
import random import time print("-------------------------- COIN FLIPPING GAME -----------------------------") choice = input("Make your choice~ (heads or tails): ") number = random.randint(1,2) if number == 1: result = "heads" elif number == 2: result = "tails" print("-------------------------------- DECIDING ...
1995aa098049e8dc96657dde5639a392ee3489f8
shubhamjha25/FunWithPython
/InteractivePrograms/lie_detector.py
311
3.90625
4
name = input("What is your name? ") while True: prompt = input("Enter a statement or RETURN to close: ") if not prompt: break check_str = name + prompt if hash(check_str.lower()) % 2 == 0: print("That is a filthy lie!") else: print("That is the truth!")
dcb892b04c98bfc762e0815df8791510e3ab7ed2
Anisha7/Tweet-Generator
/Queue.py
629
4
4
from linkedlist import LinkedList class Queue(object): def __init__(self, items = None): self.items = LinkedList(items) def enqueue(self, item): # print(self.size()) (self.items).append(item) def dequeue(self): value = self.items.head.data self.items.delete(value) ...
d1cee333a1147bc53c0040e732128b8a5d05abca
Anisha7/Tweet-Generator
/tasks1-5/rearrange.py
1,612
4.28125
4
# build a script that randomly rearranges a set of words provided as command-line arguments to the script. import sys import random # shuffles given list of words def rearrange(args): result = [] while (len(args) > 0) : i = random.randint(0, len(args)-1) result.append(args.pop(i)) ret...
bd680e184d1f735d0681428a81722c19ceab6248
lilunjiaax/JvlunlTest
/科大讯飞.py
395
3.53125
4
import sys def digui(count, count1): if count1 == count: return 0 a_muti = 1 for i in range(1, count1+1): a_muti *= i a_muti += 1 a_muti *= count1 return sum((a_muti, digui(count, count1+1))) if __name__ == "__main__": count = int(sys.stdin.readline().strip()) num =...
d9856d1782e484b89593d854eb1fe8a0a7a12041
lilunjiaax/JvlunlTest
/python实现排序算法.py
7,452
4.21875
4
""" 简单选择排序:依次遍历未排序的列表,选出其中的最小值,插在对应的位置 第一次遍历[0:n]得到最小值,排在第一个位置, 第二次遍历[1:n]得到最小值,排在第二个位置, 。。。。 """ def selectionSort(a_list): """ 选择排序 :param a_list: :return: """ a_len = len(a_list) for i in range(a_len): a_min = a_list[i] ind = i for j in range(i+1, a_len): ...
387c931fd40e7a67caea0829ff8a78740b0e7bda
lilunjiaax/JvlunlTest
/笔试题/小米测试开发.py
2,123
3.609375
4
""" 一行由正整数组成的数字字符串,和一个正整数 K,两个数据由英文逗号隔开,如:1432219,3。 输出 移除 K 位后可能的最小的数字字符串。 如 1432219 移除 4, 3, 2 这 3 个数字后得到 1219,为所有可能中的最小值。 样例输入 1432219,3 样例输出 1219 """ # while 1: # s = input().strip() # if s != '': # s = s.split(',') # m = s[0] # n = s[1] # a_list = list(m) # f...
99421affd43aacc62558b29bee4e63c4f2ba1a29
pnandini/Linked-List-1
/prob_48reversing_linked_list.py
1,286
3.765625
4
#passed leetcode #space: O(n) class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head: # for case when empty list is sent return self.recursive_reve(None, head) # recursive def recurs...
0736f71cb7b7bc0ecf84f1d00addca32477f6679
kevinczhong/Python_Exercises
/find_max_mount.py
419
3.671875
4
def max_mountain(s): start, end = 0, len(s) - 1 while start + 1 < end: mid = (start + end) // 2 if s[mid] < s[mid + 1]: start = mid else: end = mid if s[start] > s[end]: return start else: return end test_array = [1, 2, 3, 4, ...
f3299faa29411212500d21e1da8dd874cc90eb17
kevinczhong/Python_Exercises
/Lvl. 1 Exercises (Cont.)/find_largest_letter.py
770
3.875
4
import re class Solution(): def isUpper(self, str): left, right = 0, len(str) - 1 while left < right: if str[left].isupper() is True: return True elif str[right].isupper() is True: return True else: left ...
1832c705d5ce2565e3a613503f29af8f91ab5859
kevinczhong/Python_Exercises
/Lvl. 1 Exercises (Cont.)/isalphanum.py
304
3.671875
4
class Solution(): def isalphanum(self, c): if c.isalpha() is True: return True elif c.isnumeric() is True: return True else: return False s = Solution() print(s.isalphanum("a")) print(s.isalphanum("3")) print(s.isalphanum("!"))
a4c8be7f99843b46f596bf568846a42116ade319
darkhark/NBATwitterCorrelation
/src/main/python/analyzers/emotion_analyzer.py
1,113
3.5625
4
import pandas as pd from nrclex import NRCLex def __getEmotions(text): """ Get emotion affect frequencies for the input text. The values returned are continuous numbers between 0 & 1. Values are returned for the following emotions: fear, anger, trust, surprise, sadness, disgust, joy, anticipation :pa...
8308f305fc49eccd3148b71dd2c6587e235f0841
saraHumphries/vet_admin_app
/vet_app/models/calendar.py
942
3.65625
4
class Calendar: def __init__(self, appointments): self.appointments = appointments def appointments_by_day(self): ordered_appointments = sorted(self.appointments, key=lambda k: k.start_time) diary = [] for appointment in ordered_appointments: placed = False ...
5156cb17b32182f137e9f50a6aa909542bfb5c02
pzbelen/prueba1
/moodle11.py
241
3.703125
4
""" Realice un programa que muestre los números perfectos entre 1 y 1000. """ N = 1000 for i in range (1,N): suma = 0 for a in range (1,i): if i%a == 0: suma += a if suma == i: print(i)
0bafe86ee14c672a4211f5c38f73d9efd8c10673
eazook10003/solarApp
/test.py
1,298
3.84375
4
latitude = float(input("Enter the latitude: ")) longitude = float(input("Enter the longitude: ")) coordinate = [latitude, longitude] start_date = input("Enter the date in format 'mm/dd/hh': ") start_date_list = start_date.split("/") formatted_start_date = [int(start_date_list[0]), int(start_date_list[1]), int(star...
b8fc40b848771f80d7b733bdb3fb7dd5c92b7ff7
cbauerswald/SoftwareDesign
/hw3/gene_finder.py
9,296
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 11:24:42 2014 @author: Cecelia Auerswald """ # you may find it useful to import these variables (although you are not required to use them) from amino_acids import aa, codons from random import shuffle def collapse(L): """ Converts a list of strings to a string b...