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 |
|---|---|---|---|---|---|---|
e3d1598b8864ed8a3bd40b2e9f41894b5028c326 | nuneza6954/cti110 | /M4T4 P4HW2_ PoundsKilos _AliNunez.py | 951 | 4.3125 | 4 | # Program will display a table of pounds starting from 100 through 300
# (with a step value of 10) and their equivalent kilograms.
# The formula for converting pounds to kilograms is:
# kg= lb/2.2046
# Program will do a loop to display the table.
# 03-07-2019
# CTI-110 P4HW2 - Pounds to Kilos Table
# Ali Nunez... |
042bbbe47b11d62372dc4e197fbb6152468a31a5 | yash14700/leetcode-2021 | /Unsorted/1762 Buildings With an Ocean View.py | 589 | 4 | 4 | from typing import List
class Solution:
def findBuildings(self, heights: List[int]) -> List[int]:
"""
going from right to left
if the height of the current building is greater than the max so far,
add to list
reverse list and return
"""
results =... |
06b3959466ec568ffff0ef0aa9eb31d856351323 | RupesAUS/ml-labs | /lab2/lab2.py | 3,525 | 3.640625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
training = pd.read_csv("training.csv")
testing = pd.read_csv("testing.csv")
# Drop "pred_minus_obs_..." columns:
columns_to_drop = [f"pred_minus_obs_H_b{i}" for i in range(1,10)]
columns_to_drop += [f"pred_minus_obs_S_b{i}" for i in range(1,10)]
training = training.... |
8fd15296572a77732cb705283731f46b915258e9 | m-verwoert/eurovision | /eurovision_game.py | 8,434 | 3.921875 | 4 | """
This script takes a file with information on the eurovision winners of each year
which can be used to study (practice mode), take a quiz on (quiz mode) or plot
an overview of how many times a country has won (overview mode).
by Maxime Verwoert (last edit 27-05-2021)
"""
#import modules
import csv
import json
impor... |
3fa8b52e6ee94b2fdd8c2f2f8fedd08dfdaac6f6 | gozdecki/warsztaty-python | /trygonometria.py | 676 | 3.5625 | 4 | def sin(x):
if x == 90:
res = 1
elif x == 60:
res = (3**(0.5))/2
elif x == 45:
res = (2**(0.5))/2
elif x == 30:
res = 0.5
elif x == 0:
res = 0
else:
res = False
return res
def cos2(x):
if x == 0:
res = 1
elif x == 30:
res = (3**(0.5))/2
eli... |
bac393f06671575f8c870b3dc73e599736dcad37 | mingnanx/15112-termProject | /design/OldVersionCodes/TP2nd_12-2.py | 58,444 | 3.5625 | 4 | #CS112 Term Project TP2
#Mingnan Xu + Section G + mingnanx
#Animation FrameWork from CMU 15-112 Lecture Nots
#Texas Poker instruction
#Click "Start" to Begin, Press "Next" for next round
#Click "Ready" to let AI make decision
#Click "Rematch" when game over
#Press "s" for seeing the simulation proba... |
6c3e99015bf3c5a132b18f7d55dddf6b7e9952d5 | narasimhareddyprostack/Ramesh-CloudDevOps | /Python/Fours/Set/four.py | 208 | 4.40625 | 4 | s = {1,2,3}
s.update('hello')
print(s)
#The Python set update() method updates the set, adding items from other iterables.
'''
adding items form other iterable objects, such as list, set, dict, string
'''
|
ff61d43320ab6abbbd0c233a72d80420be6e8a7d | narasimhareddyprostack/Ramesh-CloudDevOps | /Python/Fours/Dict/Dict-Exe/seven.py | 289 | 4.15625 | 4 | '''
Create a new dictionary by extracting the following keys
from a below dictionary
keys = ["name", "salary"]
'''
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york" }
keys = ["name", "salary"]
newDict = {k:sampleDict[k] for k in keys}
print(newDict) |
36c9b9367b3b7ad017380332bf5dc76c3e37570d | narasimhareddyprostack/Ramesh-CloudDevOps | /Basics/e11.py | 256 | 3.578125 | 4 | """ def emp_Details(name, age):
x = "My Name is" + name
y = "My age is " + str(age)
z = "GM"
return x, y, z
a = emp_Details("Nras", 38)
print(a[0]) """
def emp(a, *b):
return a, b
a = emp('abc', 24, 'loc')
print(a)
print(a[1][0])
|
7a76892dfa40a39e0e3d76ab7905829b9fffabc7 | thechetantalwar/python-programs | /another.py | 495 | 3.90625 | 4 | def duplicate(list):
newlist =[]
# list2 = list.copy()
i = 0
while i < len(list):
j = i+1
while j < len(list):
if list[i] == list[j]:
list.remove(list[j])
else:
j = j+1
i = i+1
#for i in list:
# if i not in newli... |
1d2d011991fbdc224ecaae5ce085f7586ef497a6 | thechetantalwar/python-programs | /list.py | 184 | 4.0625 | 4 | list = ['India','UK','Canada','USA']
if 'USA' in list:
print ('there')
else:
print ('not there')
if 'Germany' not in list:
print ('not there')
else:
print ('there')
|
f22fa8b62a209b461b70a40085238da57b46eaa7 | thechetantalwar/python-programs | /excercise.py | 562 | 3.53125 | 4 | import os
import sys
def list_dir(dir_name):
return os.listdir(dir_name)
def create_file(file_name):
f = open(file_name,'w')
f.close()
def write_file(file_name,data):
f = open(file_name,'a')
f.write(data)
f.close()
dir_name = sys.argv[1]
contents = list_dir(dir_name)
count = len(contents)
f... |
2cd783d6158782d148359ff8254f90920d7b22ce | RaynardGerraldo/PyHackerRank-Solutions | /Python/Strings/designer-door-mat.py | 1,142 | 3.796875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
lw = input().split()
width = int(lw[0])
length = int(lw[1])
def reverse_design(width,length,count):
for l in reversed(range(count)):
times = l * 2 + 1
final_pattern = ".|." * times
count_pattern = math.ceil(... |
ae5fa854f14b5ab1bef97c3e20ad61f6ef3ba6b0 | djndl1/CSNotes | /algorithm/introAlgorithm/python-implementation/longest_common_sequence.py | 1,529 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
S1 = 'ACCGGTCGAGTGCGCGGAAGCCGGCCGAA'
S2 = 'GTCGTTCGGAATGCCGTTGCTCTGTAAA'
def LCS_length_recursive(X, Y):
'''
X, Y: sequences in the form of list
slow as hell
'''
if not X or not Y:
return 0
if X[-1] == Y[-1]:
return LCS_length_rec... |
1497c89d59420be3e7552a399711779d2331c78d | djndl1/CSNotes | /algorithm/introAlgorithm/python-implementation/elementary_graph.py | 3,205 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import enum
class GraphVertexColor(enum.Enum):
WHITE = 1
GRAY = 2
BLACK = 3
class GraphVertex:
def __init__(self, value):
self.value = value
self.num = 0
self.color = GraphVertexColor.WHITE
self.dist = 0
self.pre ... |
96be9ec136c4bd58d90e56a1f1b6b7e07a08f23a | djndl1/CSNotes | /algorithm/introAlgorithm/python-implementation/bubble_sort.py | 1,005 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import operator
def optimized_bubble_sort(arr, comp=operator.le):
if len(arr) < 2:
return arr
n = len(arr)
while n > 1:
next_n = 0
for i in range(1, n):
if not comp(arr[i-1], arr[i]): # if out of order, then swap
... |
d27772c86d0178fe2d20cdac998e43b6062b4654 | AYehia0/maze-solver | /maze.py | 5,343 | 3.96875 | 4 | import time
import os
from node import Node
class Maze:
""" For refering nodes to search """
def __init__(self, map):
self.map_location = map
self.map = {}
self.goal = None
self.start = None
self.map_height = None
self.map_width = None
self.space_in = ... |
c8d3c9ecec84238000de8a346cb733a023e385de | petrvanblokland/DDS-Scripting-for-graphic-designers-at-typographics-2018-06-17 | /scripts/CarWithComments.py | 5,673 | 4.53125 | 5 |
# A class can be seen as a factory of objects.
# It worth mentioning that a factory is an object too, but in this stage you can ignore that.
# class Car(object): means that we define the behavior of a Car factory, starting to make it
# inheriting from the super-generic Python "objects" class.
# It is a convention to ... |
3b314851559b0f4b7e439aef8b42393582def7e5 | raj8524/Core-python | /dubugging.py | 446 | 3.734375 | 4 | def add(x,y):
sum=x+y
return sum
if __name__=="__main__":
x=input("num1: ")
y = input("num2: ")
z=add(x,y)
print(z)
#from python terminal : python -m pdb dubugging.py
"""
n-next,c-continue,s-step intto,whatis- to get datatype of variable,where-to find to which line execution is
pdb> break 9(lin... |
53bc75fbf82418b525631f4ca4e1da824a4b4eae | raj8524/Core-python | /mysql_mini.py | 4,718 | 3.515625 | 4 | from tkinter import*
import tkinter
from tkinter import messagebox
import pymysql
''' GUI '''
windo = tkinter.Tk()
windo.geometry("700x500")
L1=Label(windo,text=" Enter device model number : ",font=('arial',30),fg='blue')
L1.grid(row=0,column=0)
E1=Entry(windo,bd=5,width=50)
E1.grid(row=0,column=1)
L2=Label(windo,t... |
0903c1568af10006e033b2daacac26e14e2b6311 | raj8524/Core-python | /DS-python.py | 16,890 | 3.734375 | 4 | # x=[100,20,6,840,50,-1,4]
# greater=x[4]
# for i in x:
# if i<greater:
# greater=i
# print(greater)
# -----------------------------------singly linked list --------------------------------
"""
class Node(object):
def __init__(self,data):
self.data=data
self.nextNode= None
class ... |
655ecd7d4f88c5327af8935c6ad7e24e681e22e8 | RuichengGeng/PythonDataStructure | /Chapter9_PriorityQueue/ArrayHeap.py | 3,103 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 1 15:30:25 2021
@author: Ruich
"""
from PriorityQueueBase import PriorityQueueBase
from PriorityQueueBase import _Item
from SortedPriorityQueue import SortedPriorityQueue
import random
import time
'''
index start from 0
left child of p is 2p + 1
right child of p is 2p +... |
b2f21f981c83b34f9a335fc5dbf9f3cc9307cef7 | RuichengGeng/PythonDataStructure | /Chapter7_LinkedList/LinkedQueue.py | 1,734 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 22:56:01 2021
@author: Ruich
"""
class Empty(Exception):
pass
class Node:
def __init__(self,element,NextNode):
self.element = element
self.next = NextNode
class LinekedQueue:
'''used linked node to implement queue'''
def __init... |
2d6a4e55b28c353176ab0eab3058c97c5bbd2ad5 | RuichengGeng/PythonDataStructure | /Chapter6_StackQueueDeques/Dequeue.py | 3,254 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 15:09:50 2021
@author: Ruich
"""
class Empty(Exception):
pass
class Dequeue:
'''circular array double end queue'''
DEFAULT_SIZE = 10
def __init__(self):
self._data = [None] * 10
self._size = 0
self._front = 0
self._back ... |
46addac7752f67b117800574a2cafb5da6760c3d | SuliacLEGUILLOU/computor | /srcs/Number.py | 1,084 | 3.96875 | 4 | """
Module de gestion des nombres complexes
"""
class Number(object):
"""
Representation d'un nombre complexe real + i * imag
"""
def __init__(self):
self.real = 0
self.imag = 0
def assign(self, r, i):
self.real = r
self.imag = i
def add(self, target):
"... |
d9dc8699f1277e00a13ab633bc3e04c9bc11ab8f | adarshsaraf123/hackerrank_solutions | /Number in Words/num_words.py | 1,086 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
tens = {0:'',10:'Ten', 11:'Eleven', 12:'Twelve', 13:'Thirteen', 14:'Fourteen', 15:'Fifteen', 16:'Sixteen', 17:'Seventeen', 18: 'Eighteen', 19:'Nineteen', 2:'Twenty', 3:'Thirty', 4: 'Forty', 5:'Fifty', 6:'Sixty', 7:'Seventy', 8:'Eighty', 9:'Ninety'}
o... |
9e095039666e4cd877fbcd4b2c434f60e6c7dd61 | adarshsaraf123/hackerrank_solutions | /Encryption/encrypt.py | 512 | 3.890625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
string = raw_input()
L = len(string)
root = math.sqrt(L)
lower = int(math.floor(root))
upper = int(math.ceil(root))
if lower*lower >= L:
rows = columns = lower
elif lower*upper >= L:
rows = lower
columns = upper
else:
rows... |
433bb4f718ff656fdafcb3a6e398654de6bf97a5 | nhthung/daily-coding-problem | /4-first-missing-int.py | 2,130 | 3.890625 | 4 | '''
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -... |
2bd337864660cda826bcdf730f2b82bf8d7d09d9 | shahidhj/Algorithms-using-Python | /QueueUsingStack.py | 515 | 3.8125 | 4 | class QueueStack:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self,value):
self.stack1.append(value)
def pop(self,value):
if not self.stack2:
while(self.stack1):
self.stack2.append(self.stack1.pop())
self.stack2.pop()
... |
668763bfcf4dc81b5ab7251d4cb53ade470afd7b | shahidhj/Algorithms-using-Python | /containsDuplicate.py | 279 | 3.71875 | 4 | A = [1,2,3,4]
def containsDuplicate(Array1):
duplicateHash = {}
for eachElement in A:
if eachElement not in duplicateHash.keys():
duplicateHash[eachElement] = 1
else:
return True
return False
C = containsDuplicate(A)
print(C) |
911731082324e7091f250aa1d3c5f64681721891 | PopMain/Python100DayPycharm | /base/string_data_struct.py | 6,128 | 4.09375 | 4 |
import sys
#string
#def println():
# print('\n')
def println(str=''):
print(str)
print('\n')
def printDivider():
divider = ''
println(divider.rjust(100, '#'))
s1 = r'\'hello, world!\''
s2 = r'\n\\hello, world!\\\n'
print(s1, s2, end='')
println()
s1 = 'hello'* 3
print(s1)
s2 = 'world'
println()
s... |
1238ee35660509d94063f5bf20b3f0de401fad7b | antonichev/netacad | /07_file-access.py | 232 | 3.78125 | 4 | file = open('devices.txt', 'a')
while True:
item = input('Enter device name (type "exit" to finish): ')
if (item == 'exit'):
break
file.write('\n' + item)
file.close()
print('file saved successfully!') |
cfdd44a717cd4be3e805c35aa122b1bc63abe828 | brentwoodcock/pythonScripts | /fiveCardPokerDraw/fiveCardPokerDraw.py | 5,272 | 3.59375 | 4 | import random
class Card (object):
RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
SUITS = ('C', 'D', 'H', 'S')
def __init__ (self, rank = 12, suit = 'S'):
if (rank in Card.RANKS):
self.rank = rank
else:
self.rank = 12
if (suit in Card.SUITS):
self.suit = suit
else:
... |
b2d4558bb9727aee59916e96a44d2f0ec21be66d | lairon27/Python | /main.py | 1,330 | 3.515625 | 4 | class Worker:
def __init__(self,name='',surname='',position='',year=0):
self._surname=surname
self._name = name
self._position=position
self._year=year
@property
def surname(self):
return self._surname
@property
def name(self):
return se... |
1b23cddd5c4bb810a48c48e4611dd7e850089949 | lairon27/Python | /Function home 1.py | 220 | 3.703125 | 4 | A = int(input("Enter A="))
B = int(input("Enter B="))
n = int(input("Enter N="))
for k in range(n):
for m in range(n):
if(k*A+m*B)<n:
print('k =',k, '\t', 'm =',m, '\t', 'k*A+m*B =',k*A+m*B) |
7353e4ea6b9b6ff4aa7e5c918f6a53b76f05004e | azurefang/projecteuler | /10.Summation of primes.py | 352 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2013-07-25 11:09:44
# @Author : azurefang (xidianft@gmail.com)
import math
def is_prime(num):
sq=int(math.sqrt(num))+1
if num%2==0 and num!=2 or num==1:
return False
for x in xrange(2,sq):
if num%x==0:
return False
return True
print... |
d461291927aa382c696bfc2ed41325c24e709ba9 | azurefang/projecteuler | /9.Special Pythagorean triplet.py | 257 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2013-07-25 10:49:43
# @Author : azurefang (xidianft@gmail.com)
import math
for a in range(1,1000):
for b in range(1,1000):
if a+b+math.sqrt(a**2+b**2)==1000:
print a*b*math.sqrt(a**2+b**2)
|
c5000db223bb64b74be5755407f46c29a75dfa98 | TBobcat/Leetcode | /Dynamic_Programming/best_sum_tab.py | 1,478 | 3.59375 | 4 |
def best_sum(num, lst):
# """
# :type num: int
# :type lst:List[int]
# :rtype: List[int], or None
# """
populate = [ None for i in range(num+1)]
# base case as to add up to 0, just pick nothing from lst,
# aka empty list, which is valid solution for 0
... |
71e803390072e49ed0909f428d71e37a0bb3c9d6 | TBobcat/Leetcode | /Dynamic_Programming/can_sum_tab.py | 941 | 3.796875 | 4 |
# can sum tabulation
def can_sum(num, lst):
## can't use dictionary as each key has no numeric relationship
## to be incremented
# this should be list of True AANNDD False
# indexed 0 ~ num, meaning at index i of populate,
# number i can be sumed by nums in list or not
populate = [False fo... |
e9dfc09020ce8682f64b107a1c8ad0d41d060345 | TBobcat/Leetcode | /defangIpAddress.py | 660 | 3.78125 | 4 | def defangIPaddr(address):
"""
:type address: str
:rtype: str
"""
## use list(str) and str.join(list_str)
## join can also be used like this
## 'abc'.join(address1.split('.')) -> '1abc1abc1abc1'
## str.replace() would also be useful
res = ""
list_address = list(addres... |
9f5634d544edb9a6e73c40c0d7725deae06d3964 | TBobcat/Leetcode | /SingleNumber.py | 580 | 3.59375 | 4 | def singleNumber(nums):
"""
:type nums: List[int]
:rtype: int
"""
d = {}
for num in nums:
if num in d:
d[num] = d[num] + 1
else:
d[num] = 1
# print(d)
# print(list(d.values()).index(1))
# print(list(d.keys()))
return l... |
99b71f3b737456b6916d801929159ba767e85a55 | TBobcat/Leetcode | /CountPrimes.py | 1,234 | 4.25 | 4 | def countPrimes( n):
"""
:type n: int
:rtype: int
"""
prime_list=is_prime(n)
# print(prime_list)
return len(prime_list)
def is_prime(n):
# based on Sieve of Eratosthenes
result = []
if n <=1 :
return []
# Create a boolean array "prime[0..n]" a... |
bdd1d533edbe1dd3ed4fa111bcf83b17ab0ae39e | OwenGordon/SearchAlgorithmAnalysis | /code/old_files/random_search.py | 23,572 | 3.703125 | 4 | # These are the algorithms that can search a random board:
# uninformed_search
# best_first_search
# a_star
# beam_search
import random
import math
import time
import matplotlib.pyplot as plt
import noise
import sys
import heapq
size = 100
dimension = 2
weight_factor = 10
obstacles = 10
weight_matrix = [[0 for x in ... |
be918ac7cd0a2955f03947a9551617c594f6739e | miiawen/miia | /python_class.py | 3,090 | 4.40625 | 4 | """
作业1
用类和面向对象的思想,“描述”生活中任意接触到的东西(比如动物、小说里面的人物,不做限制,随意发挥),数量为5个。
"""
# 1.定义一个公司员工类
class Staff:
# 定义一个构造函数,赋予员工属性:工号,姓名,年龄,性别,职位
def __init__(self,num,name,age,gender,position):
self.num=num
self.name=name
self.age=age
self.gender=gender
self.position=position
# 定义方法:工作
def wor... |
e19d001fa89e189159f02bc70314c4dbdc4ebe6f | pierredepascale/PyED | /src/pyed/fundamental.py | 2,376 | 4.15625 | 4 | #
# PyED -- an emacs like text editor in Python
#
# Copyright 2011 Pierre De Pascale (pierre.depascale _AT_ gmail.com)
#
from keymap import *
from mode import *
from command import *
from editor import *
FUNDAMENTAL_MAP = Keymap()
FUNDAMENTAL_MODE = Mode("Fundamental", "Fundamental mode", FUNDAMENTAL_MA... |
2d0d6b1b8837dadcf93338d07f2894db8e8d9801 | JJongBin/first-repo | /hello.py | 89 | 3.84375 | 4 | for i in range(1, 10+1):
if i % 3 == 0:
print('zero')
else:
print(i)
|
f67363dfe768f243e358dda358f033dab4a0ecb1 | asifkhan000/MAI1103_repo | /day_2/student.py | 260 | 3.640625 | 4 | #opening file
student = open("data.txt.txt",'wt')
#while loop
i = 1
while True:
if(i<=2):
khan = raw_input("enter name >>")
salman = student.write(khan+"\n")
i=i +1
else:
break
student.close()
|
b4ab5c05860d95676bdc24b9813226002a49fc0f | fgarcialainez/RabbitMQ-Python-Tutorial | /rabbitmq/tutorial1/receive.py | 1,191 | 4.3125 | 4 | #!/usr/bin/env python
"""
In this part of the tutorial we'll write two small programs in Python; a producer (sender) that sends a single
message, and a consumer (receiver) that receives messages and prints them out. It's a "Hello World" of messaging.
https://www.rabbitmq.com/tutorials/tutorial-one-python.html
"""... |
fb515dd959590df1d4b8b35413381ca5028d2f21 | fgarcialainez/RabbitMQ-Python-Tutorial | /rabbitmq/tutorial3/receive_logs.py | 1,369 | 3.875 | 4 | #!/usr/bin/env python
"""
In this part of the tutorial we'll deliver a message to multiple
consumers. This pattern is known as "publish/subscribe".
https://www.rabbitmq.com/tutorials/tutorial-three-python.html
"""
import pika
def callback(ch, method, properties, body):
print(" [x] %r" % body.decode("utf-8"... |
83792da495de2cde80fd634e8f5462678724ea8e | oskip/IB_Algorithms | /CountAndSay.py | 1,012 | 3.765625 | 4 | # The count-and-say sequence is the sequence of integers beginning as follows:
#
# 1, 11, 21, 1211, 111221, ...
# 1 is read off as one 1 or 11.
# 11 is read off as two 1s or 21.
#
# 21 is read off as one 2, then one 1 or 1211.
#
# Given an integer n, generate the nth sequence.
#
# Note: The sequence of integers will be... |
04699c309198e4994163d4e0c2d4fb5f034913d4 | oskip/IB_Algorithms | /NextPointer.py | 892 | 3.8125 | 4 | # Definition for a binary tree node
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
nodes = [root.left, root.right]... |
350a65972f601a457c42bd2a1c1ce2b93473043e | oskip/IB_Algorithms | /Rotate2D.py | 706 | 3.8125 | 4 | # You are given an n x n 2D matrix representing an image.
#
# Rotate the image by 90 degrees (clockwise).
#
# You need to do this in place.
#
# Note that if you end up using an additional array, you will only receive partial score.
#
class Solution:
# @param A : list of list of integers
# @return the same lis... |
5a6cc3ea333878df2fa29ba83fdc357abaa8aa14 | oskip/IB_Algorithms | /BSTIterator.py | 2,197 | 4.03125 | 4 | # Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
#
# The first call to next() will return the smallest number in BST. Calling next() again will return the next smallest number in the BST, and so on.
#
# Note: next() and hasNext() should run in aver... |
63a44c5b5e8e7d4859b9b427984aa055e4c7b2f7 | oskip/IB_Algorithms | /Single2.py | 641 | 3.6875 | 4 | # Given an array of integers, every element appears thrice except for one which occurs once.
#
# Find that element which does not appear thrice.
#
# Note: Your algorithm should have a linear runtime complexity.
#
# Could you implement it without using extra memory?
#
# Example :
#
# Input : [1, 2, 4, 3, 3, 2, 2, 3, 1, ... |
c3e29afaa4b37b9edceee1dc5ac836158b57c54e | oskip/IB_Algorithms | /Combinations.py | 1,062 | 3.71875 | 4 | # Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n.
#
# Make sure the combinations are sorted.
#
# To elaborate,
# 1. Within every entry, elements should be sorted. [1, 4] is a valid entry while [4, 1] is not.
# 2. Entries should be sorted within themselves.
#
# Example :
# I... |
3286229a89987d397de1446f030dcf398500a9cc | oskip/IB_Algorithms | /LsZero.py | 801 | 3.578125 | 4 | # Find the largest continuous sequence in a array which sums to zero.
#
# Example:
#
#
# Input: {1 ,2 ,-2 ,4 ,-4}
# Output: {2 ,-2 ,4 ,-4}
#
# NOTE : If there are multiple correct answers, return the sequence which occurs first in the array.
class Solution:
# @param A : list of integers
# @return a list of ... |
a7b0001a9a204a24607419abd86197464487e184 | oskip/IB_Algorithms | /Merge.py | 1,152 | 4.1875 | 4 | # Given two sorted integer arrays A and B, merge B into A as one sorted array.
#
# Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code.
# TIP: C users, please malloc the result into a new array and return the result.
# If the number of elements initialized in A and... |
9381dbe0b76aa28cbf37d4818d33bdb528866282 | oskip/IB_Algorithms | /WindowStr.py | 1,805 | 3.78125 | 4 | # Given a string S and a string T, find the minimum window in S which will contain all the characters in T in linear time complexity.
# Note that when the count of a character C in T is N, then the count of C in minimum window in S should be atleast N.
#
# Example :
#
# S = "ADOBECODEBANC"
# T = "ABC"
# Minimum window ... |
81afe70547b88e2216f90d93e901d89282ae7628 | oskip/IB_Algorithms | /RevListSample.py | 914 | 4.25 | 4 | # Reverse a linked list. Do it in-place and in one-pass.
#
# For example:
# Given 1->2->3->4->5->NULL,
#
# return 5->4->3->2->1->NULL.
#
# PROBLEM APPROACH :
#
# Complete solution code in the hints
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = ... |
7cd1b1d8bc85b30db5346d51bf84a6e11d35a5ca | oskip/IB_Algorithms | /AddNum.py | 1,010 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param A : head node of linked list
# @param B : head node of linked list
# @return the head node in the linked list
def addTwoNumbers(self, A, B):
if... |
0d308d25c3bf724af92a70bcf56a90b79ac8846f | oskip/IB_Algorithms | /Recover.py | 861 | 3.703125 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return a list of integers
def recoverTree(self, root):
self.el1 = None
self.el2 = None
... |
f4a9fc20f5686ae331df6db5a29c4bc07b6ba01d | oskip/IB_Algorithms | /Histogram.py | 1,924 | 3.796875 | 4 | # -*- coding: utf-8 -*-
# Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
#
# Example Histogram
# http://i.imgur.com/1OutEEI.png
# Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]... |
462afcbdefdcb99675d8421d65f39c600436c71c | oskip/IB_Algorithms | /MinStack.py | 1,303 | 3.828125 | 4 | # Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
#
# push(x) - Push element x onto stack.
# pop() - Removes the element on top of the stack.
# top() - Get the top element.
# getMin() - Retrieve the minimum element in the stack.
# Note that all the operations have to be... |
9546bdb5bc36efc4bc2bafbcea33051e0688048c | lgreco/Algorithms | /Dijkstra shortest-path/naive_dijkstra.py | 5,690 | 4.0625 | 4 | """
Naive implementation of Dijkstra's shortest-path algorithm. This implementation
serves as a "conversation starter" to justify the need for using a min-heap, as
well as a more structured approach to capturing and representing a graph.
leo@cs.luc.edu
"""
# The graph is ... |
effe89200265e8f329221cca7044b4b41f814feb | ismailsunni/scripts | /foobargoogle1.py | 574 | 3.71875 | 4 | import math
def check_prime(number, primes):
limit = math.sqrt(number)
for prime in primes:
if prime > limit:
return True
if number % prime == 0:
return False
return True
def solution(i):
primes = []
number = 2
while len(primes) < (i + 5):
is_p... |
9431f2f8c0c10c09878199baf743b0d1f3510781 | pr1malbyt3s/Py_Projects | /Advent_of_Code/2021/1_2021.py | 1,183 | 4.4375 | 4 | # AOC 2021 Day 1
import sys
# This function is used to read a file input from the command line. It returns the file contents as a list of lines.
def read_file() -> list:
if len(sys.argv) != 2:
print("Specify puzzle input file")
sys.exit(-1)
else:
# Open file at command line position 1:... |
abbda68a1e2777bae2bdc1ec1903232c81d7d42f | pr1malbyt3s/Py_Projects | /Runcode.ninja/Simple_Addition.py | 1,116 | 4.1875 | 4 | #!/usr/bin/env python3
# This script accepts an input file of mixed value pairs separated by lines.
# It check that each value pair can be added and if so, prints the corresponding sum.
import sys
from decimal import Decimal
# Create a master list of all number pairs.
numList = []
# Type check function to determine... |
1d9e1c21898c5bff05445b2e9eb70e7100ce3ede | pr1malbyt3s/Py_Projects | /Coderbyte/Codeland_Username_Validation.py | 926 | 3.578125 | 4 | # Checking to see if a supplied username meets the criteria:
# 1. Is between 4 and 25 characters
# 2. Starts with a letter
# 3. Contains only letters, numbers, and the underscore character
# 4. Does not end with an underscore
# Valid regex solution is r"^[a-zA-Z][\w_]{2,23}[^_]$"
def CodelandUsernameValidation(strPara... |
b98d347fd0ae7a3165a96243dd7da330847ba4b8 | pr1malbyt3s/Py_Projects | /Runcode.ninja/White_Socks_With_Boots.py | 447 | 3.546875 | 4 | #!/usr/bin/env python3
# This is a simple script to demonstrate connecting to a raw socket and parsing received data.
import sys
import socket
# Get host and port from command line.
HOST = sys.argv[1]
PORT = int(sys.argv[2])
#IP = socket.gethostbyname(HOST)
# Create and connect to socket. Print received data.
s = s... |
dd49bbd3212bd1c77674f3b8f68ef134a6f7b253 | pr1malbyt3s/Py_Projects | /Runcode.ninja/Simple_Cipher.py | 579 | 4.28125 | 4 | #!/usr/bin/env python3
# This script is used to decode a special 'cipher'.
# The cipher pattern is each first word in a new sentence.
import sys
# Create a list to store each parsed first word from an input file.
message = []
with open(sys.argv[1], 'r') as f:
cipher = f.read()
# While reading file, split the file ... |
aaff01f4c50117175b3fa2ff67846621c4305534 | pr1malbyt3s/Py_Projects | /Advent_of_Code/2019/Day1_2019.py | 379 | 3.828125 | 4 | #!/usr/bin/python3
import math
# Open the file for reading and create masses list.
with open('day1.txt') as f:
masses = (map(int, f.read().splitlines()))
# Create the fuel variable.
fuel = 0
# Iterate through list of masses. Calculate req for each. Add req to fuel.
for mass in masses:
req = math.floor(mass/... |
ac0ef21febfd8f26eeec7ae27c2bee55b35ab46f | pr1malbyt3s/Py_Projects | /Runcode.ninja/Third_Letter_Is_A_Charm.py | 946 | 4.21875 | 4 | #!/usr/bin/env python3
# This script accepts an input file containing words with misplaced letters.
# Conveniently, the misplaced letter is always from the third position in the word and is at the beginning.
import sys
# rotate function to perform letter rotation on a provided string.
# It first checks to ensure the... |
bd1d7b33054c84e94bf40ba0211b3e08364d7cae | geekygirlsarah/adventofcode-2017 | /day03/day03part2.py | 1,705 | 3.953125 | 4 | # Advent of Code 2017
# Day 3, Part 2
# @geekygirlsarah
from math import sqrt, ceil
# Files to run through
# input.txt being the input the puzzle provides
# inputFile = "input.txt"
inputFile = "testinput.txt"
# Variables
# Process file
with open(inputFile) as f:
while True:
numberInput = f.readline(-1)... |
47ae52992cd01ea67e56c6f6816b60f70ac189f8 | geekygirlsarah/adventofcode-2017 | /day05/day05part1.py | 1,082 | 3.953125 | 4 | # Advent of Code 2017
# Day 5, Part 1
# @geekygirlsarah
# Files to run through
# input.txt being the input the puzzle provides
inputFile = "input.txt"
# inputFile = "testinput.txt"
# Variables
numbers = []
max_length = 0
pointer = 0
steps = 0
# Process file
with open(inputFile) as f:
while True:
contents... |
6f653d27d31b3b3b3509f6fbefd9b4b40b53147f | gkouvas/Hangman | /Topics/Search in a string/Simon says/main.py | 228 | 3.84375 | 4 | def what_to_do(instructions):
if instructions.startswith("Simon says") is True or instructions.endswith("Simon says") is True:
return "I " + instructions.replace("Simon says", "").strip()
return "I won't do it!"
|
2a0dbd36d8681e20ab57c2cb4e3a08644147ca45 | clelandgt/Python | /Assignments/sort/insert_sort.py | 562 | 4.03125 | 4 | # -*- coding:utf-8 -*-
__author__ = 'cleland'
def insert_sort(l):
""" 插入排序
从左到右是从小到大
伪代码:
for i in [1, n)
for j in [0, i):
if a[i] <= a[j]:
swap(a[i], a[j])
"""
for i in xrange(1, len(l)):
for j in xrange(0, i):
if l[i] <=... |
a351976707232262f51f04f958cb556dfb1db6da | clelandgt/Python | /BasicPractice/trains_backup/lib/routes.py | 6,218 | 3.78125 | 4 | # -*- coding: utf-8 -*-
from stations import Station
from town import Town
TOWNS_NAME_LIST = "ABCDE"
NO_ROUTE = "NO SUCH ROUTE"
class Routes:
route_table = {}
def __init__(self, file_path):
assert self.read_file(file_path) == True
def read_file(self, file_path):
try:
file ... |
69d8675f741aade1c0eaf7b1cfe995859481effa | clelandgt/Python | /DesignPatterns/IteratorPattern/numeral_system.py | 2,640 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @File : numeral_system.py
# @Author: clelandgt@163.com
# @Date : 2020-08-14
# @Desc :
class Customer:
"""客户"""
def __init__(self, name):
self.__name = name
self.__num = 0
self.__clinic = None
def get_name(self):
return self.__name
def regi... |
c49a9ae0052a42b68f8e39aeab2b0e2dccfcef3a | Ekl1p5e/Python-Scripts | /second.py | 181 | 3.703125 | 4 | # Read in file
intfile = input()
# Split file by space
intlist = list(map(int, intfile.split()))
# Divide sum of integers by number of integers
print(sum(intlist) / len(intlist))
|
8dc5a9f8b53bcb847f6e8bd807ad2b97813f69a5 | tuananh1406/BAI_TAP_LPYTHON2009 | /bai_tap_buoi_2.py | 1,191 | 3.546875 | 4 | #! coding: utf-8
'''
Đề bài: Hôm nay là ngày nghỉ, Ben cùng chơi một trò chơi với các bạn của mình.Luật trò chơi rất đơn giản, mỗi người sẽ nhận được một con số nguyên dươnggồm có 5 chữ số. Nếu ai có số nút từ con số này là lớn nhất thì chiến thắng.Hãy giúp Ben tính xem số nút của co... |
53d6a9c097da43b9a3eaca4d67ecd80fe992e80e | Vinicius42-00/Problemas-UVA-Online-Judge | /Passwords_complete_search.py | 1,457 | 3.921875 | 4 | # Para fazer as combinacoes
# https://docs.python.org/3/library/itertools.html
from itertools import product
import sys
def get_input_list():
qtd_palavras = input()
palavras = []
regras = []
for i in range(1, int(qtd_palavras) + 1): # Assumption: ...words greater than 0
palavras.append(sys.stdi... |
3345a2121cf0a799856a3faf108be44b51dffdb4 | donndurk/fyp | /trees.py | 1,430 | 3.515625 | 4 | def algorithm_P(n):
a = ['(' if i%2==0 else ')' for i in range(2*n)]
a.insert(0, ')')
m = (2 * n) -1
while True:
# input("Next?")
val = a[1:]
return_sequence(val)
a[m] = ')'
if a[m-1] == ')':
a[m-1] = '('
m -= 1
else:
j... |
b010487c9cbfa00dff938d01eef26cb3ac961f5d | 7avenged/Rainfall_pred | /kaggle3441.py | 5,358 | 3.84375 | 4 | #LOAD THE MODULES## #THIS ONE FOR LR ONLY
#INPUT THE STATE, MONTH, YEAR
#IF STATE== STATE-1
# IF MONTH== 1ST MONTH
###FOR STATE-1 #######
######FOR 1ST MONTH#####
#LOAD THE DATA -
#YEAR COLUMN-X
#RAINFALL LEVEL- Y
#FIT AND PRINT THE PREDICTION
#####FOR 2ND MONTH#########
#DO THE SAME
###################... |
01ddb32ed932b9e12751c413dd412ad26ce6825b | ssalteko/Corona_w_pandas | /covid_plotting.py | 2,061 | 3.640625 | 4 | import matplotlib.pyplot as plt
from covid_panda import *
import pandas as pd
def plot_global_regions(df, dtype, regions,start):
''' plot global df and label for legend. '''
df = df.set_index('Country/Region').T[regions]
l = df.count()
for region in regions:
plt.plot(df[f'{region}'][... |
4091cebd158a9c74db8ffc837eae4e30f4f8449f | billy-yoyo/textart | /textart.py | 42,660 | 4.3125 | 4 | import math
import traceback
class Art:
# internal method to help calculate if a point is inside a triangle
# p1, p2, p3 = points [x, y]
@staticmethod
def _sign(p1, p2, p3):
return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
# internal method to calculate whet... |
d3db1753332fe7cfb41ed9f5e53bc408f214ff3c | HomaiRS/Face_Detection_Recognition_CNN | /FaceRecognition_CNN.py | 3,743 | 3.953125 | 4 | import PIL.Image
import PIL.ImageDraw
import face_recognition
import numpy as np
# ------------> Face detection <------------ #
# Load the clear file into a numpy array
image = face_recognition.load_image_file("/Users/homai/Desktop/myFaceRecognition/Exercise Files/myImgs/ma1.jpg") #/Users/homai/Desktop/myFaceRecognit... |
4c64ed35d0a53d1b79709553f9719ed2a5eea0fb | irsol/LeetCode | /137. Single Number.py | 918 | 3.828125 | 4 | # 137. Single Number 2
# Given a non-empty array of integers, every element appears three times except for one,
# which appears exactly once. Find that single one.
#
# Your algorithm should have a linear runtime complexity.
# Could you implement it without using extra memory?
#
# Example 1:
#
# Input: [2,2,3,2]
# Outpu... |
812a8a7dac1e22b1bdbd9e47f3c59113b303aa0c | seaboltthomas19/Monty-Hall-Problem | /monty-hall-sim.py | 1,111 | 4.1875 | 4 | import random
switch_was_correct = 0
no_switch_was_correct = 0
print("====================================" +
"\n" +
"*** Monty Hall Problem Simulator ***" +
"\n" +
"====================================")
print("Doors to choose from: ")
doors = int(input())
print("Iterations to r... |
d5cd6b64899147dd33672d4cdb5fd8ff868b1955 | rjayswal-pythonista/DSA_Python | /NumberofPaths.py | 887 | 3.640625 | 4 | # Created by Roshan Jayswal
# Copyright © AppMillers. All rights reserved.
# Number of paths to reach the last cell with given cost in 2D array
def numberOfPaths(twoDArray, row, col, cost):
if cost < 0:
return 0
elif row == 0 and col == 0:
if twoDArray[0][0] - cost == 0:
retur... |
3f5ff96ec69bcff03af8e5a82ae3ea3fe3ec8360 | rjayswal-pythonista/DSA_Python | /CheckBalanced.py | 838 | 3.875 | 4 | # Created by Roshan Jayswal
# Copyright © AppMillers. All rights reserved.
# Balanced Tree
def isBalancedHelper(root):
if root is None:
return 0
leftHeight = isBalancedHelper(root.left)
if leftHeight == -1:
return -1
rightHeight = isBalancedHelper(root.right)
if rightHeight ==... |
8c998c084f50628965811b375c65921a4df1522a | AyaanaPS/LearningSystems | /Week8/polynomialKernels.py | 2,695 | 3.5 | 4 | import csv
from sklearn.svm import SVC
import numpy as np
import math
# These stand for how the data should be classified.
firstVal = 1.0
secondVal = 5.0
Cval = math.pow(10,6)
degreeVal = 5
# This classifies the test data using the firstVal and secondVal
xDataTest = []
yDataTest = []
with open('features.test.csv', 'r... |
e4fc02f63f2a02fcec2c06b979b4dd6e69490bfb | linyork88/11-30-line-robot | /app.py | 389 | 3.578125 | 4 | # while 迴圈
result=0
n=1
while n<=10:
result+=n
n+=1
print(result)
#for 迴圈
#for 變數 in 列表:
result=0
#for n in range(1,11): 1~10
for n in [5,7,2]: #5+7+2
result+=n
print(result)
#函式
def test(n1,n2):
return n1+n2
result=test(3,4)
print(result)
# 讀取檔案
file=open("data.txt", mode="r")
da... |
d6e2ddc7419a818102d17faaa20ce2111f54b006 | eugenechantk/cs152-harnessing-ai-algorithm | /Final Project/ConnectFourSolver.py | 3,352 | 3.53125 | 4 | #Implemented from my past assignment
#Use to flatten the state of the 2d board so to allow hashing
def flatten(board):
# if it's nested lists, flatten them. I do this with list comprehension taking each tile at a time from each sublist
if type(board[1])==list:
board = [item for sublist in board for item... |
128536f88651a78f1340d6123579ca06a0468872 | shuowenwei/LeetCodePython | /Easy/LC189RotateArray.py | 1,108 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/rotate-array/
"""
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
"""
... |
dc9d1b0ca483bb95ab3d87f74bf356292e01699a | shuowenwei/LeetCodePython | /Hard/LC410.py | 1,462 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/split-array-largest-sum/
https://labuladong.gitee.io/algo/2/21/63/
https://mp.weixin.qq.com/s/E2cyJwMVxRosaU2-bZyTjA
LC704, LC34, LC875, LC1101, LC410
"""
class Solution(object):
def splitArray(self, nums, m):
"""
:ty... |
884925766827950a8c940d2682a72a5888645054 | shuowenwei/LeetCodePython | /OutOfBag/AWS/minPermutation.py | 1,671 | 3.5 | 4 | import math
# Add any extra import statements you may need here
# Add any helper functions you may need here
def minOperations(arr):
# Write your code here
n = len(arr)
target = ''.join([str(i) for i in sorted(arr)])
cur = ''.join([str(i) for i in arr])
import collections
q = collections.deque()
visited... |
3f571950d681b782d2571387388427a9e5507ce4 | shuowenwei/LeetCodePython | /Medium/LC380.py | 2,649 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/insert-delete-getrandom-o1/
solution: https://leetcode.com/problems/insert-delete-getrandom-o1/discuss/85397/Simple-solution-in-Python
https://labuladong.gitee.io/algo/2/22/65/
对于 getRandom 方法,如果想「等概率」且「在 O(1) 的时间」取出元素,一定要满足:底层用数组实现,且数组... |
a65e19df73d711ef28ecdc6a7eb1f6178867cc7e | shuowenwei/LeetCodePython | /Medium/LC199.py | 1,460 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/binary-tree-right-side-view/
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class... |
093e654d943cb8f8e57de7f37a4352ff36e8ba9f | shuowenwei/LeetCodePython | /Hard/LC224.py | 3,826 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/basic-calculator/
solution: https://leetcode.com/problems/basic-calculator/discuss/62424/Python-concise-solution-with-stack.
https://labuladong.gitee.io/algo/4/32/136/
LC43, LC224, LC227, LC772, LC150
"""
import collections
class Soluti... |
141f4ce894c26d313a55de94b4d8e062744003e3 | shuowenwei/LeetCodePython | /OutOfBag/Robinhood/house_street_trades.py | 1,508 | 3.515625 | 4 | # refer to: https://leetcode.com/discuss/interview-question/882324/robinhood-phone-screen
from collections import Counter
class TradesMatcher:
def filter_matching_trades(self, tradesA, tradesB):
"""
tradesA: List[str]
tradesB: List[str]
return: List[str]
"""
aCoun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.