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
142c3a880a995d272de26e0bfc2cea57b65f8faf
thinkSharp/Interviews
/prime.py
816
3.734375
4
import math def generatingPrime(num): def cross_off(local_prime): i = local_prime + local_prime while i < len(flags) - 1: flags[i] = False i += local_prime def get_next(local_prime): if local_prime >= len(flags): return 0 while not flags[loc...
9b491fd9f17fe7beca81e66ff26d5b2c06e349f2
thinkSharp/Interviews
/knapsack.py
742
3.515625
4
def knapsack(profits, weights, capacity): memo = {} max_profit = 0 lw, lp = len(weights), len(profits) def recursive(index, p, rem): nonlocal max_profit if index == lw or rem == 0: if max_profit < p: max_profit = p memo[index] = max_profit ...
a405af4106b23e64a0d20ca735199c73aba2f631
thinkSharp/Interviews
/FindDuplicate.py
775
3.59375
4
def find_duplicate(input, input_size): def get_bit(local_arr, pos): byte_pos = pos // 32 bit_pos = pos % 32 return local_arr[byte_pos] & (1 << bit_pos) def set_bit(local_arr, pos): byte_pos = pos >> 5 # right shift 5 means divide by 32 = 2 ^ 5 bit_pos = pos & 0x1F # 0x1F...
9aa3783793118171b5f79bccdc98376141f77559
thinkSharp/Interviews
/hasPalindrome.py
769
3.734375
4
def isPalindrome(input, ignore_white=True): len_str = len(input) word_dict = {} for l in input.lower(): if l in word_dict: word_dict[l] += 1 else: word_dict[l] = 1 odd_count = 0 white_count = 0 for k, v in word_dict.items(): if k == ' ' and igno...
b7bf080254862459e7f57aa6e4c47930d775b0ff
NYU-Python-Intermediate-Legacy/rkahn-ipy-solutions
/rkahn-2.1.py
942
3.65625
4
#!/usr/bin/env python import os import sys sendmail_prog = '/usr/sbin/sendmail' required_args = set(['to', 'from']) valid_args = set(['to', 'from', 'subject', 'body']) args = sys.argv[1:] argdict = {} for arg in args: key, val = arg.split('=') argdict[key] = val #check for unfilled required fields missing_fiel...
446ee8fa9b00d59f4ff43507ddd3329e2a95072c
jnucanwin/LeetCode
/LeetCode/树/235. 二叉搜索树的最近公共祖先.py
871
3.65625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if (p.val >= root.val and q.val <= root.val) or (p.val <= root.val and q.v...
9e414762286b253382524b496f95aca5cc826ec6
jnucanwin/LeetCode
/LeetCode/树/traverse.py
1,650
3.5625
4
import queue def PreOrder(T): S = [] p = T while S or p: if p: print(p.val) S.append(p) p = p.left else: p = S.pop() p = p.right def InOrder(T): S = [] p = T while S or p: if p: ...
a7a14a3b03aab74efdd52a67fa8309eb6db1fed6
ITHaron/ITHaron.github.io
/task/QuadraticEquations(1).py
973
3.953125
4
import math print("Введите коэффициенты для квадратного уравнения (ax^2 + bx + c = 0):") print("Введите значение а:") a = int(input()) print("Введите значение b:") b = int(input()) print("Введите значение c:") c = int(input()) if a == 0: if b == 0: if c == 0: print("0==0") else: ...
490a08ac4512e7a511982b7af940439b7357e843
kunaljha5/python_learn_101
/bob/challenge3/solution1.py
312
4.09375
4
def largest_sum (arr): if len (arr) == 0: return print('Too Small') max_sum = current_sum = arr[0] for num in arr[1:]: current_sum = max(current_sum + num, num) max_sum = max(current_sum, max_sum) return max_sum print(largest_sum([7,1,2,3,4,5,6,10, -12, 3, 21, -19]))
78d416dc01860974fa287e30c23a393215a322a7
kunaljha5/python_learn_101
/bob/challenge1/solution1.py
430
4.0625
4
# using sorted in built function def anagram(s1, s2): # remove white spaces and convert all to lower case s1 = s1.replace(" ", "").lower() s2 = s2.replace(" ", "").lower() return sorted(s1) == sorted(s2) print(anagram("dog", "d go")) print(anagram("public relations", "crap built on lies")) print(an...
91e32dc173b88a2cbdb441627633957137064961
kunaljha5/python_learn_101
/scripts/pyhton_list_operations_remove_pop_insert_append_sort.py
1,554
4.25
4
# https://www.hackerrank.com/challenges/python-lists/problem #Consider a list (list = []). You can perform the following commands: # insert i e: Insert integer at position. # print: Print the list. # remove e: Delete the first occurrence of integer. # append e: Insert integer at the end of the list. # ...
1a7388e27c93c8eac99096e442a4f6a5251ec778
josue270193/python_simple_banking_system
/Topics/Class instances/Right triangle/main.py
512
3.828125
4
class RightTriangle: def __init__(self, hyp, leg_1, leg_2): self.c = hyp self.a = leg_1 self.b = leg_2 # calculate the area here if hyp * hyp == leg_1 * leg_1 + leg_2 * leg_2: self.area = f"{(0.5 * leg_1 * leg_2):.1f}" else: self.area = "Not ri...
763be1fc5f63303f431bac2371c2c4b939107f05
JohnRoesler/my-learning
/Python/Test2.py
618
3.671875
4
import string fname = raw_input("Enter file name: ") if len(fname)<1: fname = "words.txt" fh = open(fname) wordcount = dict() #put all words into dictionary with count of each word for line in fh: line = line.translate(None, string.punctuation) line = line.lower() words = line.split() for word...
ac6e987109f21d8eaddecab8f964be75e8604a36
JohnRoesler/my-learning
/Python/PP/TempConv.py
637
4.03125
4
while True: temp = raw_input("Enter a temperature: ") try: temp = int(temp) break except: print "Please enter a valid integer temperature!\n" continue while True: conv = raw_input("Would you like to covert to Fahrenheit (F) or Celcius (C)? ") if conv == "...
b9cad236fe3cfa00de968a1231097dc2bec7b887
RamAmireddy/problem_solving
/Python3_programs/testNestedfun.py
535
4.0625
4
# def print_msg(msg): # # This is the outer enclosing function # # def printer(): # # This is the nested function # nonlocal # msg=msg*2 # print(msg) # # printer() # # # We execute the function # # Output: Hello # print_msg("Hello") a = 100 def outer_function(): a = 5 def inner_f...
fb125e9a5aabf9710e773a71c248456a0691cb54
RamAmireddy/problem_solving
/Python3_programs/leapyear.py
805
3.828125
4
import math as mt mt.sqrt(5) def is_leap_year(x): if x%4 == 0 : if x%400 != 0 : return False else: return True else: return False # print(is_leap_year(5)) # for i in range(5,0,-2): # print(i,end=' ') # class point(): # # # # import heapq # ls = [[1...
5938dac74c63bf4cc52f2d209224fdc678fefc59
RamAmireddy/problem_solving
/Python3_programs/mergelinkedlists.py
1,378
3.640625
4
def mergeTwoLists( l1, l2): if l1 is None: return l2 elif l2 is None: return l1 """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = l1 if l1.val < l2.val else l2 prev=None while (l1 and l2): if (l1.val < l2.val): if l1.next ...
e17b30380b88b93b144712844ff07a0176fc50f7
RamAmireddy/problem_solving
/Python3_programs/seg_tree_oddeven_count.py
2,561
3.609375
4
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' # Write your code here class NumArray(): def __init__(self, n...
3a95699c2332e8a78a1609466f15989fe5d2c1b5
stevesea/py4e
/ex06_05.py
308
3.78125
4
# Write code using find() and string slicing (see section 6.10) to extract the # number at the end of the line below. Convert the extracted value to a floating # point number and print it out. text = "X-DSPAM-Confidence: 0.8475" ind = text.find(":") substr = text[ind+1:] print (float(substr.strip()))
aa17cbf952a28b83b353b33a01666c22b88c0700
deven-s/SeleniumWIthPythonPractices
/OopsPython.py
405
3.796875
4
class Vehicle: numberOfWheels = None def printNumOfWheels(self): print("numebr of wheels = ", self.numberOfWheels) class twoV(Vehicle): def __init__(self, wheels): Vehicle.numberOfWheels = wheels class fourV(Vehicle): def __init__(self, wheels): Vehicle.numberOfWheels = wheel...
6f834a420be88f8731f77f9bdf2b7d6e36c690d3
deven-s/SeleniumWIthPythonPractices
/OppsOfPython/Inheritance.py
882
3.90625
4
# parent class constructor getting called class Person(object): def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) def details(self): print("My name is {}".format(self.name)) ...
186883aa182b8d87b6fc026628e14b1dfb066258
capoch/AdventOfCode2019
/10/10.2.py
1,577
3.515625
4
# Solution approach: # Transforming map of asteroids to a map in polar coordinates with the center on the Laser # and the angle is measured from starting position of the laser clockwise (same way the laser turns) # We then are looking for the 200th angle (counting by raising size starting with 0). # Then find the polar...
ac271ef63c0838e4a814c31077b377f39dabcac4
kiilopapa/CodeClubClasses
/classes_practice.py
4,411
4.09375
4
# This is a class class Cat: def __init__(self, name, age): # [0], [1] self.name = name # [2] self.age = age def react_to(self, stimulus): # [3] if stimulus == "pet": if self.age < 1: return self.name + " bites and scratches you!" elif self.a...
f532e7850d1a1a7e63a7d5dd17dff788419b4410
Terairk/SEACSTA_Round2
/Input_Data/test 4.py
200
3.90625
4
age = int(input("Please insert your age")) if age < 11: print("You must be in primary") elif age < 19: print("You must be in secondary") else: print("You must have graduated high school")
7d180da0bcf7f111d1d306897566ec129cd5ef0e
mebsahle/data-structure-and-algorithms
/sorting-algorithms/pancakeSort.py
882
4.125
4
# Python code of Pancake Sorting Algorithm def maxNum(arr, size): num = 0 for index in range(0, size+1): if arr[index] > arr[num] : num = index return num def flipArr(arr, index): begin = 0 while begin < index : temp = arr[begin] ...
9596a350c5d963a9a85fe8425ef3b87338210afe
mebsahle/data-structure-and-algorithms
/palindrome_checker.py
345
3.890625
4
def palindrome_checker(string): counter = {} for i in range(26): counter[chr(ord('a') + i)] = 0 for s in string: counter[s] += 1 odd = 0 for c in counter: if counter[c] % 2 != 0: if odd == 0: odd = 1 else: retu...
6ba305ade67ff01bc59afa2a78e0043adbb92c0d
mebsahle/data-structure-and-algorithms
/DSU/DSU.py
1,080
3.875
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.V= vertices self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def find_parent(self, parent,i): if parent[i] == -1: return i ...
ba83ea2b590e328087f71dd225166751d2aead87
aditigarg06/MyWork
/TopologicalSort.py
887
3.578125
4
class Node: def __init__(self,val): self.val = val self.parent = None self.completionTime = 0 self.visited = 0 A = Node('A') B = Node('B') C = Node('C') D = Node('D') E = Node('E') F = Node('F') graph = { A: [B, C], B: [A, D, E], C: [A, F], D: [B], ...
5f03d9498638838e154eb14dc5d071654e415233
aditigarg06/MyWork
/files_from_old_mac/Breadth_First_Search.py
1,110
4.03125
4
import queue class Node: def __init__(self ,key): self.data = key self.parent = None self.distance = None self.visited = 0 def BFS(source): source.distance = 0 source.visited= 1 Queue = queue.Queue(maxsize= len(graph)) Queue.put(source) while not Queue.empty(): ...
adb4432ffbf1532e3842951a97b1a9b106ddae2c
chriscremer/Other_Code
/neural_net/Neural_Net_CC/NN_cc.py
11,280
3.765625
4
import numpy as np import random import pickle from costs import * from activations import * class Network(): def __init__(self, layer_sizes, activations, cost=CrossEntropyCost, regularization='l2', weights_n_biases=None): """The list ``layers`` contains the number of neurons in the respective ...
a0376c35ee2c4e04b86ece321b9ddeb8215df84f
chriscremer/Other_Code
/other/Sorting/selection_sort.py
573
3.84375
4
import numpy as np def selection_sort(unsorted): #go through, find min, swap it with first # go though starting at second spot, find min, put it in second spot # continue # time: O(n^2) # space: O(1) for i in range(len(unsorted)): #find min value current_min = unsorted[i] current_min_index = i for ...
56d78f20d2514fd7a917e937059ac05964ac2986
Ashutos-h/python-L12
/1.py
190
3.796875
4
#Answer 1 with open("test.txt") as f: list=f.readlines() n=int(input("Enter the line from where you want to read the file:")) for i in range(n-1,len(list)): print(list[i]) f.close()
1fc8ec40758d4f61d3d3b1317075633d9e769f5a
octabytes/FireO
/src/fireo/database/database.py
1,727
3.59375
4
from fireo.database.errors import DBConnectionError from google.cloud import firestore class Database: """Create connection with google cloud firestore Responsible to create and verify connection is successfully establish. If you’re running in Compute Engine or App Engine, authentication should “just wor...
4005b0cdbc825e1aa4733e362e48bcce0f63a171
Lossless-Virtual-Switching/Backdraft
/exp/multi_run.py
1,280
3.78125
4
#!/usr/bin/python3 """ This scripts is a helper tool for running a program (in this context an experiment) for multiple times and store its results in a file. """ import os import subprocess import argparse def run_program(program, args): cmd = '{} {}'.format(program, args) print(cmd) res = subprocess.che...
657cc579b23092de91a13c6695341267c759a0aa
rajeshnailwal/learnpython
/evalexample.py
167
4.25
4
#Example of 'eval' x = eval(input("Enter any type of value and check whether eval converts with its actual type : ")) print("value of x =",x,"and type is =",type(x))
e7b86c5920aed86f96942647cbf5306d39cd6c0a
mvigoda/Coursera
/Neural_Networks/simple_numpy.py
1,881
4.09375
4
import numpy as np def sigmoid(x): s = 1/(1 + np.exp(-x)) return s def sigmoid_derivative(x): s = sigmoid(x) ds = s*(1-s) return ds x = np.array([1, 2, 3]) print x print(np.exp(x)) # result is (exp(1), exp(2), exp(3)) print 'x = np.array([1, 2, 3])' x = np.array([1, 2, 3]) print (x ...
17ef4805330c3fbf2ddd1e7ebd8523bb81f0c658
Russmania101/ECE434_Russell_Johnson
/hw01/EtchASketch.py
2,980
3.890625
4
#!/usr/bin/env python # Russell Johnson # ECE434 # Homework 1 import pygame, sys from pygame.locals import * # global variables white = (255, 255, 255) black = (0, 0, 0) maxScreenLength = 800 minScreenLength = 100 minPosition = 0 positionBuffer = 100 fps = 80 dotSize = 4 def main(): pygame.init() # get scr...
90ed5a586bd4038fd8715575d8fab9eec9f03b4c
Arun4080/Machine-Learning
/Data_Visualisation using matplotlib/1. 2D Graphing - line graph.py
432
3.75
4
#Arun import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') #data x=[5,8,10] y=[12,16,6] x2=[6,9,12] y2=[9,13,10] #Plotting to our canvas plt.plot(x,y,'g',label='line 1',linewidth=5) plt.plot(x2,y2,'r',label='line 2',linewidth=5) #info for notation on graph plt.title('Epic Info') plt.yla...
2bd763d943e6e4df90d5684fbc5ae29c6b8fa68d
Arun4080/Machine-Learning
/deep_Learning/neural_network/mnist/train.py
3,484
3.78125
4
import pandas as pd import numpy as np train=pd.read_csv("data/train.csv") train_X=(train.drop(["label"],axis=1)/255).values train_Y=pd.get_dummies([str(i) for i in train.label]).values del(train) class Neural_Network(object): def __init__(self): #parameters self.inputSize = 784 self.hl1Size = 20 self...
602680049ebc03ecfd95c4df4b8cbfd92876fe99
kamalkkv/guvigithub
/1_3_6.py
101
3.53125
4
n=int(input()) l=[] for i in range(n): a=int(input()) l.append(a) l.sort() print(l)
8d968d5a0f2fc2c19e123229a53af0372045996e
kamalkkv/guvigithub
/1_4_10.py
135
3.796875
4
n=int(input()) a=1 b=1 print(a,end=" ") print(b,end=" ") for i in range(n-2): c=a+b a=b b=c print(c,end=" ")
37655ebf3527047a0d508d82218f8d422a3308ab
kamalkkv/guvigithub
/1_6_6.py
147
3.671875
4
s=input() if(s.isnumeric()): print('No') elif(s.isalpha()): print('No') elif(s.isalnum()): print('Yes') else: print('No')
d658aa0cc672f3454fa0e4551a870d276403398d
kamalkkv/guvigithub
/1_9_3.py
308
3.6875
4
while(True): s=input() if(len(s)==0): break if('%' in s): i=s.index('%') if('/' in s): i=s.index('/') s1=s[0:i] s2=s[i+1:] x=int(s1) y=int(s2) if(s[i]=='%'): print(x%y) if(s[i]=='/'): print(x//y)
be49657803020bad23c30a31486f9aa90b64728c
kamalkkv/guvigithub
/1_4_8.py
73
3.515625
4
a=int(input()) b=int(input()) a=a^b b=a^b a=a^b print(a) print(b)
1adbffb5c026d1eb981941709e1bb80e5191f402
koopuluri/random
/dna_sequence.py
1,992
3.65625
4
def build_state_machine(s): """ State machine represented as: [{vocab_option: next_index}] @param s: string to build state machine for """ # building the options for the start state: # possible options from each char is the unique characters within the input string: vocab = set(s) # ...
259853deed909a64d9da9ff866dc1ed7f4bbded2
gkerkar/PySpark
/etl/birds/birds_pyspark.py
3,026
3.796875
4
# -*- coding: utf-8 -*- """Birds PySpark.ipynb PySpark ETL with DataFrames and without SparkSQL. """ # !pip install pyspark # import PySpark Libraries from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, StringType, DoubleType, IntegerType from pyspark.sql.functions import ud...
488e3c344d7dcaa57b2e8e6d525f79afca927029
lizhe960118/Data-Science
/python/little_python_project/quick_sort_new.py
513
4
4
def quicksort(arr): return quick_sort(arr, 0, len(arr) - 1) def quick_sort(arr, start, end): if start >= end: return point = arr[start] lp = start lr = end while lp < lr: while arr[lr] > point and lp < lr: lr -= 1 arr[lp] = arr[lr] while arr[lp] < poi...
92dce00b0cc901bf399fe9419628111ef80b5a3d
Tanx-123/Assassin
/multithreading.py
542
3.625
4
import time import threading def square(number): print("Square of the number:") for i in number: time.sleep(0.2) print("Square:",i*i) def cube(number1): print("cube of the number:") for i in number1: time.sleep(0.2) print("Cube of the nubmer:",i*i*i) ar=[2,3,5,6] t=time.t...
0bb65cb9b5d9e6b30d70b2613cc224cb39c24d5e
balanalina/Formal-Languages-and-Compiler-Design
/Scanner/symbol_table/linked_list.py
1,973
4.21875
4
# class for a Node class Node: def __init__(self, val=None): self.val = val # holds the value of the node self.nextNode = None # holds the next node # implementation of a singly linked list class LinkedList: def __init__(self, head=None): self.headNode = head self.size = 0 ...
089ae0817fd751511c247c7a27d3fd79c12a94f8
vignesh0710/DS-and-Algorithms
/Binary Search/recursive_search.py
450
3.78125
4
def recur_bin_search(arr,start,end,numb): if start> end: return -1 else: mid = int((start+end)/2) if numb == arr[mid]: return ("Number found", mid) elif numb < arr[mid]: return recur_bin_search(arr, start,mid-1,numb) else: return r...
6b4c9df3141aea511823da489918089bd9e0d3f0
carterwilkie/02_Area_Perim_Calc
/06_coffee_order.py
329
4.09375
4
print() print("*** Coffee Order Demo ***") keep_going = "" while keep_going == "": want_coffee = input(" Do you want coffee? ") if want_coffee != "yes": print("wrong answer, you always want coffee") continue else: print("Good choice") break print() print("End of program")...
ce0294d390f0a177ec3aeda038dc5fcbcbba7605
AnetaStoycheva/Programming101_HackBulgaria
/Application/fill_tetrahedron.py
336
3.578125
4
from math import sqrt def fill_tetrahedron(num): return ((num ** 3) / (6 * sqrt(2))) / 1000 def main(): print(fill_tetrahedron(100)) print("{0:.2f}".format(fill_tetrahedron(100))) print(fill_tetrahedron(200)) print(fill_tetrahedron(160)) print(fill_tetrahedron(110)) if __name__ == '__main...
9cc51642d3e7db9599aba01035d05c276988e056
carolyan1/python-challenge
/PyBank/python-challenge/PyBank Challenge.py
4,123
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[3]: #The total number of months included in the dataset # The net total amount of "Profit/Losses" over the entire period # Calculate the changes in "Profit/Losses" over the entire period, then find the average of those changes # The greatest increase in profits (date and am...
d6ab4c7c743384dcd2ed27bfb8c892ade3edf548
AdamBioprinter/OpenCV-Python-Tutorials
/opencv/ImageProc/Contours/startContour.py
2,703
3.53125
4
# contours are curves joining all continous points having the same color # or intesnity # it is recommended to use binary images - apply threshold beforehand # the findCoontours function DOES modify the source image # the function finds white objects in a black background # syntax: # cv2.findCountrous(src, contour r...
859ef481f45ed61bf9d6fb2423f64a02ed9571e3
NanGonglin/PythonBase
/class03/ex02.py
1,665
3.984375
4
# -*- coding: utf-8 -*- """ @Time : 2021/3/10 14:14 @Auth : sy @Function :请输入模块功能描述 """ # 列表 name = [] print(id(name)) name = ['will', 'roy', '土匪'] print(name) # 每一个值都相当于一个变量 name = ['will', 'roy', '土匪', 1, True, 1.1] print(name) # 列表的增加 # append在列表的末尾添加 name.append('sy') print(name) # insert在指定位置添加元素 # 下标,从0开始,到列表长度...
d359688356138f29cc3ffa8fc3018fdf93ee157b
NanGonglin/PythonBase
/class03/ex03.py
545
3.875
4
# -*- coding: utf-8 -*- """ @Time : 2021/3/10 14:14 @Auth : sy @Function :请输入模块功能描述 """ # 元组 tup = () print(type(tup)) tup = (1,) print(type(tup)) tup = (1, 2) print(type(tup)) # 元组的增删改,不支持 # tup.append(2) # del tup[1] # 元组的查找 print(tup[1]) # 成员遍历 for t in tup: print(t) # 下标遍历 for i in range(len(tup)): print...
01d6945ec1f7b4383ecbb973c6511795ba2cfd93
expmud/sudokuSolver
/sudoku_solver.py
2,297
3.75
4
from collections import defaultdict class SudokuSolver(): def solveSudoku(self, board): def place_number(d, i, j): rows[i][d] += 1 columns[j][d] += 1 boxes[box_index(i, j)][d] += 1 board[i][j] = str(d) def remove_number(d, i, j): del ro...
d57187946a853ffb691cb1ceab5d16caac37f2a4
wasimusu/RL
/classic_control/classic_control_game.py
4,657
3.515625
4
import gym import numpy as np import matplotlib.pyplot as plt np.random.seed(2) # For repeatable experiments Q = {} gamma = 1 def discrete(state, weights=(1, 2)): """ Discretize the states """ return tuple(np.round(attribute, weights[index]) for index, attribute in enumerate(state)) class GameAgent: ...
4cffac416c9cb06943fbdd3e1463d823b911c755
michaelbrave/Homemade-CS-Degree
/Languages-Other/Python/FreeCodeCamp_Learn_Pyhton(completed)/guessingGame.py
232
3.859375
4
secret_word = "kenobi" guess = "" count = 0 limit = 5 while guess != secret_word and count < limit: guess = input("enter a guess: ") count += 1 if count == limit: print("out of guesses") else: print("you win")
ac9c9f1eee8e36c225165822ae1d0782e89e0cd6
quookka/pyspark-streamlit-tutorial
/src/session3/sparksql.py
2,242
3.984375
4
import streamlit as st from pyspark.rdd import RDD from pyspark.sql import DataFrame from pyspark.sql import SparkSession from pyspark.sql.types import * def create_dataframe(spark: SparkSession, rdd: RDD, schema: StructType) -> DataFrame: """Generate a DataFrame from a RDD of Rows and a schema. We assume th...
d0cb3e53cb9f1757859577fc55005072d06c4173
Boyne272/Blackjack
/src/blackjack/player.py
1,275
3.765625
4
"""Class for the player, with a score and a valid hand.""" from typing import Callable from blackjack.deck import Card class Player: """Holds the players score and hand.""" def __init__( self, name: str = 'player', strategy: Callable = None ): self.name = name self...
851923444eaff28c1d56a3e51bc30914e8fd180e
Tanbourine/EternalDeckTracker
/Archive/guitest.py
1,825
3.515625
4
from tkinter import * from tkinter import ttk from tkinter import messagebox def quit_app(): root.quit() def show_about(event=None): messagebox.showwarning( "About", "Button Clicked" ) root = Tk() # ------- File Menu ---------# the_menu = Menu(root) file_menu = Menu(the_menu, tearof...
8e8d0d71f0f2cb1df7d42c4f701956ee2e605084
vanka857/MinersArchers
/MinersArchers/game/dispatcher/Dispatcher_console.py
3,152
3.546875
4
from game.dispatcher.Dispatcher import Dispatcher COMMANDS = {"create": 0, "move": 0, "attack": 0, "upgrade": 0, "build": 0, "quit": 0} class ConsoleDispatcher(Dispatcher): def __init__(self): super().__init__() # print("Console Dispatcher is ready!") def get_command(self): print("y...
2b274c1f446021f171ef1ba30f5d969fa4f048d6
Khandelr/Elements-of-AI
/Othello - Part1/khandelr.py
4,631
3.5625
4
import sys import gamePlay from random import randint from copy import deepcopy """ Weight assigned to each row and column for a matrix and based on this score is calculated """ weight=[ [300, -40, 30, 30, 30, 30, -40, 300], [-40, -80, -20, -20, -20, -20, -80, -40], [40, -20, 20, 20, 20, 20, -20, 40], [40, -...
ff778e9613f73174d93722beb4d8a9918b5ca345
congtranxuan/python-challenge
/PyPoll/main.py
2,676
4
4
import os import csv #get the path to the csv data file csvpath = os.path.join("Resources","election_data.csv") #create an output text file in the same folder with main.py textpath = os.path.join("..","PyPoll","Election_Results.txt") #open the csv file and read data into csvfile with open(csvpath,newline ="") as csvf...
eca7a855c0fd51f3a35a6a5e7b5fbee6addf7070
seanbudd/scikit-image
/doc/examples/numpy_operations/plot_camera_numpy.py
802
3.765625
4
""" Using simple NumPy operations for manipulating images ===================================================== This script illustrates how to use basic NumPy operations, such as slicing, masking and fancy indexing, in order to modify the pixel values of an image. """ import numpy as np from skimage import data impor...
61dd0d18efb8c9f967d10a579353783017cd8dce
seanbudd/scikit-image
/doc/examples/filters/plot_denoise.py
3,184
3.78125
4
""" ==================== Denoising a picture ==================== In this example, we denoise a noisy version of a picture using the total variation, bilateral, and wavelet denoising filters. Total variation and bilateral algorithms typically produce "posterized" images with flat domains separated by sharp edges. It ...
9c2a3b21e73d8ae04b8f6279bc61ce4c8935ffe9
xenonyu/leetcode
/BFS/openLock.py
1,495
3.546875
4
from typing import List class Solution: def openLock(self, deadends: List[str], target: str) -> int: q1 = set(['0000']) q2 = set([target]) visit = set() step = 0 def updown(inStr, index, up=True): before = inStr[0:index] after = inStr[index + 1:] ...
093ae12b0a1a1c1299e3df04f014d02319e085a3
xenonyu/leetcode
/isValid.py
1,463
3.609375
4
class Solution: def isValid(self, s: str) -> bool: if len(s) % 2 == 1: return False pairs = { ")": "(", "]": "[", "}": "{", } stack = list() for ch in s: if ch in pairs: if not stack or stack.pop() !...
69f41de6581912364b309c84f7c164e02d6a89b6
xenonyu/leetcode
/DFS/lowestCommonAncestor.py
1,168
3.65625
4
import handleInput # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestCommonAncestorForBTree(self, root: TreeNode, p: int, q: int) -> TreeNode: if root.val < p and root.val < q:...
b8f7b1069a72211812ce829118f5c0ddcdf5c758
xenonyu/leetcode
/replaceSpace.py
289
3.578125
4
class Solution: def replaceSpace(self, s: str) -> str: s = list(s) for i in range(len(s)): if s[i] == " ": s[i] = "%20" return "".join(s) if __name__ == "__main__": test = Solution() ans = test.replaceSpace("We are happy.") print(ans)
7aada2e96c5afcf62addf26a4afa972cb0cad6ad
xenonyu/leetcode
/searchRange.py
1,004
3.546875
4
from typing import List class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: l, r = 0, len(nums) - 1 res = [-1, -1] def leftBound(l, r, target): while l <= r: mid = l + (r - l) // 2 if nums[mid] >= target: ...
f198b8fd12ff650c88b897a5c7360ff0d074b918
HurricaneSKC/Practice
/WarriorsgameOOP.py
2,945
3.875
4
import random import math # Create warrior class with initialise method class Warrior: # define attribues - name, health, maximum attack, maximum block def __init__(self, fname="Warrior", health="0", maxattack="0", maxblock="0" ): self.fname = fname self.health = health self.maxattack = m...
b63fd63b6a381fd59a4e1f0eb1fef04bdc7886d7
HurricaneSKC/Practice
/Ifelseproblem.py
535
4.28125
4
# Basic problem utilising if and elif statements # Take the users age input and determine what level of education the user should be in age = int(input("Enter your age: ")) # Handle under 5's if age < 5: print("Too young for school") # If the age is 5 Go to Kindergarten elif age == 5: print ("Go to Kindergar...
56ff2ec0d608fe22ec4c4a8acf6d0f7789e61f91
HurricaneSKC/Practice
/FunctionEquation.py
614
4.1875
4
# Problem 10: Create an equation solver, functions # solve for x # x + 4 = 9 # x will always be the first value recieved and you will only deal with addition # Create a function that takes an input equation as a string to solve for x as above example def string_function(equation): # separate the function using the s...
14c04eb9f94b09aa6c49cf516ce2163d607b53e9
XRFXLP/Puzzle-and-CSP-solvers
/SlidingPuzzleSolver.py
7,310
3.671875
4
''' An efficient simple program to solve sliding puzzle game of variable sizes ''' from copy import deepcopy from functools import reduce from time import sleep class node: def __init__(self, loc): self.loc = loc self.parent = None def __eq__(self, other): return self.loc == other.loc ...
fc64ae88890dd66365a2ed43daa92b27cd503224
Ronaldss/Python
/exercicios/operadores-logicos.py
405
4.21875
4
# -*- coding: utf-8 -*- # Cometários # Operações matemáticas + - * / ** % # Variáveis # Operadores relacionais == != < > <= >= # OPERADORES LOGICOS and or not ''' x = 2 y = 3 print(x == y and x > y) print(x != y or x < y) ''' # Exemplo com NOT nome = input('Qual o seu nome: ') if not nome =...
8d13ed1af283339b42bd8c64c42a0417fdf5b316
Ronaldss/Python
/exercicios/revisao/operadores-logicos-review.py
410
4.03125
4
# Operadores Logicos # and or not a = 100 b = 200 c = 300 d = 10 print('A: ' + str(a)) print('B: ' + str(b)) print('C: ' + str(c)) print('D: ' + str(d)) if a < b and a > d: print('A eh menor que B e maior que D.') if b > a or d >= c: print('B eh maior que A ou D eh maior ou igual a C') if not(a > b): ...
01128016296190edce2e8c2a203fe2f40dda23c5
Ronaldss/Python
/exercicios/revisao/string-metodos-geral2-review.py
881
4.4375
4
# Revisao: Strings - métodos mais usado em geral print('Concatenando strings') string1 = 'Estou estudando ' string2 = 'a linguagem de programacao Python' print('Concatenacao: ' + string1 + string2) print('\n') print('Contar quantos caracteres existem no texto em questao: ') texto = 'My name is Ronald.' tamanho = l...
03e6d663c7d1d8d6a13919e38eab134cb3c77e55
codingscode/python-rapid
/meu_teste/016.py
1,215
3.734375
4
from datetime import datetime print('----------- inicio ------------') frutas = ['jabuticaba', 'laranja', 'ata', 'jaca', 'graviola'] for cada in frutas: minha_fruta = f'Nome: {cada:12} - número de letras: {len(cada): 3}' print(minha_fruta) print() pi = 3.14159265359 meu_numero = f'o numero pi é: {pi:.1f}'...
3f3f4756e41307f2e2c45ad490183771b2ca9b5b
codingscode/python-rapid
/scripts/script16.py
288
3.59375
4
frase1 = "Eu amo comer amoras no café da manhã" lista_termos1 = frase1.split() print(lista_termos1) frase2 = "Amora abacaxi abacate banana" lista_termos2 = frase2.split() print(lista_termos2) frase3 = "Carro,moto,avião" lista_termos3 = frase3.split(',') print(lista_termos3)
4610e7c6b33338931982eb200f8caef18fa55f28
FaiyazMujawar/telegram-bot
/utils/utils.py
1,441
3.75
4
def get_meaning_text(result: dict): meaning_string = [ f'*{result["word"][0].upper()}{result["word"][1:]}*\n', f'Pronunciation: _{result["phonetics"]}_\n', ] # Adding the synonyms to the list synonyms = result["synonyms"] if len(synonyms) != 0: meaning_string.append( ...
6d0cea7ff2fe8358a00551db80cd103a74654d72
Danilo657/ex079
/ex079.py
399
4.03125
4
numeros = list() resp = '' while True: valores = int(input('diga um valor: ')) if valores not in numeros: numeros.append(valores) print('valor inserido com sucessos') else: print('valor duplicado !!!') resp = str(input('Quer continuar ? Sim ou Não ?')).strip().upper()[0] if ...
edefad039b683995c7e0a695094c2d90653fe02e
benjdj6/Hackerrank
/Algorithms/Sorting/RunTimeofAlgorithms.py
338
3.765625
4
def insertionSort(l): shift = 0 for i in xrange(1, len(l)): j = i - 1 key = l[i] while (j >= 0) and (l[j] > key): l[j + 1] = l[j] j -= 1 shift += 1 l[j + 1] = key print shift m = input() ar = [int(i) for i in raw_input().strip().split()] ...
c3bd0685bcceacb2bee2ae1cc40bb24aff0cd71c
benjdj6/Hackerrank
/DataStructures/LinkedList/ReverseDoublyLinkedList.py
533
4.125
4
""" Reverse a doubly linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node return the head node of the updated list """ de...
e293198871ec08424c67ad2a37021ef5c44d861d
benjdj6/Hackerrank
/30DaysofCode/8-DictionariesAndMaps.py
302
3.65625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(raw_input()) book = {} for i in range(n): s = raw_input().split(' ') book[s[0]] = s[1] while True: q = raw_input() if q in book: print "{0}={1}".format(q, book[q]) else: print "Not found"
b4c6f4ec5e914ae0aa50f8263e9740c93f261383
benjdj6/Hackerrank
/DataStructures/LinkedList/DeleteDuplicateValues.py
568
3.9375
4
""" Delete duplicate nodes head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def RemoveDuplicates(head): du...
4540179c6aae504f043a386eec4df995e8b0f773
benjdj6/Hackerrank
/Python/Strings/SwapCase.py
248
4
4
# Enter your code here. Read input from STDIN. Print output to STDOUT ls = list(raw_input()) result = [] for char in ls: if char.isupper(): result.append(char.lower()) else: result.append(char.upper()) print ''.join(result)
478efc27cbb4f305f734318d05801268f96f6d23
benjdj6/Hackerrank
/Algorithms/Sorting/InsertionSort-Part2.py
585
3.71875
4
#!/bin/python def insertionSort(ar): for i in range(0, len(ar)): if i < len(ar) - 1: if ar[i] > ar[i+1]: for j in range(i+1,0,-1): if ar[j] < ar[j-1]: temp = ar[j-1] ar[j-1] = ar[j] ar...
24a46259273ab1ffe3550cbeb6578b14d9f92600
Harshad06/Python_programs
/PANDAS/ops1.py
500
3.890625
4
# importing pandas as pd import pandas as pd # Creating the DataFrame df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Print the dataframe # print(df) # Operation 1 df['Discounted_Price...
d2cb42f27bc8a03906e7f19d28a0bc75467053a3
Harshad06/Python_programs
/py-programs/args-kwargs.py
442
4.28125
4
# args/kwargs allows python functions to accept # arbitary/unspecified amount of arguments & keyword arguments. # Arguments def print_args(*args): print(f"These are my arguments : {args}") print_args([1,2,3],(20,30),{'key': 4}, 'abc') #--------------------------------------------------- # Keyword Arguments def...
a81393a5f71a79fcf1b9bcc44698fdd66ca24be1
Harshad06/Python_programs
/PANDAS/joinsPandas.py
739
4.125
4
## MERGE Function # JOINS in PANDAS ----> [inner/outer/right/left/index] # importing pandas import pandas as pd # Creating Dictionary 1 data1 = {'id': [1, 2, 10, 12], 'val1': ['a', 'b', 'c', 'd']} a = pd.DataFrame(data1) # print(a) # Creating Dictionary 2 data2 = {'id': [1, 2, 9, 8], 'val2': ['p', 'q', '...
1b504b774f87f662641549baee8860ea34fd6fa7
Harshad06/Python_programs
/useful-functions/accumulate.py
389
4.1875
4
""" accumulate() function > accumulate() belongs to “itertools” module > accumulate() returns a iterator containing the intermediate results. > The last number of the iterator returned is operation value of the list. """ import itertools import operator n = [1,2,3,5,10] print(list(itertools.accumulate(n, op...
e34ed0465a5fd22c905826be81eda95e1bba69d4
Harshad06/Python_programs
/PANDAS/joinsIdenticalData.py
740
4.21875
4
import pandas as pd df1 = pd.DataFrame([1,1], columns=['col_A'] ) #print("DataFrame #1: \n", df1) df2 = pd.DataFrame([1,1,1], columns=['col_A'] ) #print("DataFrame #2: \n", df2) df3 = pd.merge(df1, df2, on='col_A', how='inner') print("DataFrame after inner join: \n", df3) # Output: 2x3 --> 6 times it will be ...
563a50b28ee25e6f59fbf34f21543b52f3ed8f65
Harshad06/Python_programs
/Higher complexity programs/reverseList.py
354
3.859375
4
# Reverse list without using any built-in method. lst = [1,2,3,4,5,6,7,8,90,100] length = len(lst) for i in range(length): print(lst[length-i-1], end=" ") # 100 90 8 7 6 5 4 3 2 1 """ lst = ["Apple", "Banana", "Orange", "Kiwi", "Strawberry", "Mango"] length = len(lst) for i in range(length): pr...
a86bcefb27c6457d02ae369a4bea970c49d2d4bc
Harshad06/Python_programs
/Higher complexity programs/reverseListContent.py
348
3.9375
4
# Reverse a list along with each element in that list. lst = ['123', '456', '789'] rev_char = [x[::-1] for x in lst] print(rev_char) # ['321', '654', '987'] length = len(rev_char) for i in range(length): print(rev_char[length-i-1], end=" ") # 987 654 321 # print(lst[::-1]) # wor...
3d2940c4c69c25deb55ec0edd17891d636361f8a
Harshad06/Python_programs
/py-programs/convertListToTuple.py
152
4.03125
4
# Python3 program to convert a # list into a tuple def convert(list): return tuple(list) # Driver function list = [1, 2, 3, 4] print(convert(list))
c1ecf3355aadf69e8084b30d801024003c562702
Harshad06/Python_programs
/Dictionary/sortDict.py
471
4.46875
4
# To sort a dictionary - # this will sort by key c={2:3, 1:89, 4:5, 3:0} y = sorted(c.items()) #print(y) #Another excampple of sort by key d = { "John":36, "Lucy":24, "Albert":32, "Peter":18, "Bill":41 } y = sorted(d.keys()) print(y) x = sorted(d.values()) print(x) z = sorted(d.items()) print(z) for k,v in d...
22d5bf5edffbed91678726571008ad5bbdcf7df3
Harshad06/Python_programs
/TEST FILES/cybage.py
1,699
3.65625
4
''' class Test: h = 10 _h = 20 __h = 30 class B(Test,Test2): pass print(Test.h) print(Test._h) print(Test._Test__h) ''' ''' class A: def display(self): print("Class A") class B(A): def display(self): print("Class B") def display2(self): print("Class B") cl...
b51beeb8b02807df87114bcb9af74d5b3842a18e
Harshad06/Python_programs
/useful-functions/lambda.py
201
3.6875
4
f = lambda x,y : x+y print(f(4,5)) f = lambda x,y : x**y print(f(2,2)) # Factorial f = lambda n: 1 if n==0 else n*f(n-1) print(f(5)) # max of x & y max = lambda x,y: x if x>y else y print(max(8,5))