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
c7c4b6e6a0c260674afdd1da8272aa30d5e5f792
hihello-jy/portfolio
/2055-실습3-거북이제어.py
337
4.09375
4
#거북이 제어 프로그램 import turtle t=turtle.Turtle() t.width(3) t.shape("turtle") t.shapesize(3,3) while True: command=input("명령을 입력하시오: ") if command =="l": t.left(90) t.forward(100) elif command=="r": t.right(90) t.forward(100) else: command
5f7f389fd301595d75ef96bb67922db3ab6009e7
hihello-jy/portfolio
/2034연습문제1- 두수의 합차곱~.py
245
3.828125
4
x=int(input("x: ")) y=int(input("y: ")) print("두수의 합: ",x+y) print("두수의 차: ",x-y) print("두수의 곱: ",x*y) print("두수의 평균: ",(x+y)/2) print("큰수: ",max(x,y)) print("작은수 : ",min(x,y))
bbda8737a33110a256d8161048191a03428c0616
hihello-jy/portfolio
/문제05- 엘레베이터 프로그램.py
649
3.9375
4
def goDown(): for i in range (current_floor-1,target_floor,-1): print ("현재 %d층 입니다." %(i)) print("%d층에 도착하였습니다." %target_floor) def goUP(): for i in range (current_floor+1,target_floor): print ("현재 %d층 입니다." %(i)) print("%d층에 도착하였습니다." %target_floor) current_floor=int(input("현재 층: ")) target_floor=int(input("가는 층: ")) floor=[1,2,3,4,5] if target_floor==current_floor or target_floor not in floor: print("다른층(1~5)을 눌러주세요.") elif current_floor < target_floor: goUP() else: goDown()
c81d31947a5a55aba7db6189877302d48432ee66
hihello-jy/portfolio
/문제09- 문자열의 aeiou개수 세기.py
442
3.71875
4
#소문자! aeiou의 개수를 각각 출력하는 프로그램. #문자열은 영문 알파벳만 입력한다고 가정하자. aeiou=['a','e','i','o','u'] text=input("문자열을 입력하세요: ") found={} found['a']=0 found['e']=0 found['i']=0 found['o']=0 found['u']=0 for letter in text: if letter in aeiou: found[letter] += 1 for k,v in sorted(found.items()): print('%s: %d' %(k,v),end=', ')
5308b888a4dd93ac9d4c21bd9853a77becb943a9
hihello-jy/portfolio
/2034연습문제2-원기둥부피.py
107
3.578125
4
r=float(input("r: ")) h=float(input("h: ")) vol=3.141592*r**2*h print("원기둥의 부피: ",vol)
268933a63618a04223937184b6e4ac3ef7434170
hihello-jy/portfolio
/if else- 놀이기구 탑승 나이, 키.py
241
4.03125
4
age = int(input("나이를 입력하세요: ")) height = int(input("키를 입력하세요: ")) if ( age >= 10 ) and ( height >= 165): print ("놀이기구를 탈 수 있다.") else: print ("놀이기구를 탈 수 없다.")
956a2bef2795a208453c065a0355496b97b3562a
hihello-jy/portfolio
/2024 변수연습문제7-밭전.py
524
3.546875
4
import turtle t=turtle.Turtle() t.shape("turtle") side=50 angle=90 t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(side) t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(100) t.right(180) t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(side) t.forward(side) t.right(angle) t.forward(side) t.right(angle) t.forward(side)
7ef6d3d4d033a58a1caf44dce617424d78fdb25b
SongMunseon/softwareproject-5
/20171631-서필립-assignment2.py
360
4.03125
4
n = int(input("Enter a number : ")) f = 1 while n>=0: for i in range(1,n+1) : f *= i print(n,"! =", f) f = 1 n = int(input("Enter a number : ")) if n < -1 : print("Can't execute") for i in range(1,n+1) : f *= 1 f = 1 n = int(input("Enter a number : ")) elif n == -1 : break
46108fef98238e6fe945219751b4f9242f4cc854
ghzwireless/cubeos
/test/integration/jenkinsnode/cistack/binfile.py
6,172
3.546875
4
import os import sys import re import magic from utils import supportedBoards class Binfile(object): """ A binary file object that contains the name, file type, path, target architecture, and target board type. Internal methods include file and path validation, attempts to determine target architecture and file type, and a series of variable return methods. """ def __init__(self, name = '', path = '', board = ''): self.board = board self.name = name self.path = path self.arch = None self.filetype = None self.abspath = None def validate(self): """trap conditions with no / no matching arguments for 'board'""" print("Checking for supported board.") if self.board == "": sys.exit("Unknown board type. Exiting.") supportedboards = supportedBoards() if not self.board in supportedboards: sys.exit("Board %s is not supported." % self.board) return False if not self.getpath(): sys.exit("%s unable to find binary file to upload in \ specified path or current working directory %s. \ Exiting now." % (errstr, str(array[0]))) array = self.getfiletype() if not (array[0] or array[1]): return False self.arch = array[0] self.filetype = array[1] return True # small methods: def path(self): return self.path def board(self): return self.board def name(self): return self.name def abspath(self): return os.path.join(self.path,self.name) def arch(self): return self.arch def filetype(self): return self.filetype # Big effort to find path to binary: def getpath(self): """Try to determine the correct path and name of the binary""" cwd = os.getcwd() # if there's neither a name nor a path, puke if (self.path == "" and self.name == ""): sys.exit("Missing name and missing path. Exiting.") # if the path is specified but isn't a directory, puke if not os.path.isdir(self.path): sys.exit("%s unable to verify path %s" % (errstr, self.path)) # if there's no file at the specified path and binfile name, puke if not os.path.isfile(os.path.join(self.path, self.name)): sys.exit("%s unable to locate binary file in path %s" % (errstr, self.path)) # if self.path is defined and seems to be a real path, start checking if os.path.isdir(self.path): if os.path.isfile(os.path.join(self.path, self.name)): return True # If self.path is not present, check if binfile includes a path -- # if it does but no path is specified, it should have a path attached, # or else binfile must be in the current working directory. if (os.path.isfile(self.name) and (self.path == "")): array = os.path.split(self.name) # if it exists but the os.path.split gives nothing in the first array element, # check to see if it's in the current working directory. if not os.path.exists(array[0]): print("Unable to determine path to binary from \ input path %s." % array[0]) self.path = cwd # if there isn't anything preceding self.name, either it's in the cwd or # else it's an error condition. if os.path.isfile(os.path.join(self.path, array[1])): self.path = cwd self.name = array[1] return True else: return False # if, on the other hand, splitting the name gives a usable path--good! if os.path.exists(array[0]): self.path = array[0] self.name = array[1] return True # if the path exists else: sys.exit("%s unable to find binary file to upload in \ specified path or current working directory %s. \ Exiting now." % (errstr, str(array[0]))) return False return False # Try to determine architecture and board target from binary file: # TODO find a better way to parse which board was the target; this isn't bad # but it's hardly exact. # # NA-satbus: 'ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, not stripped' # NA-satbus .bin: 'data' # MSP430: 'ELF 32-bit LSB executable, TI msp430, version 1 (embedded), statically linked, not stripped' # MSP430 .bin: 'HIT archive data' # STM32F407-disco: 'ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, not stripped' # STM32F407-disco .bin: 'data' # Pyboard: 'ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, not stripped' # Pyboard .bin: 'data' def getfiletype(self): """Use [magic] to get some information about the binary upload file.""" d = magic.from_file(os.path.join(self.path,self.name)) d = re.sub(', ',',',d) e = d.split(',') filetype = e[0] array = [False,False] if filetype == 'data': array = ['ARM','BIN'] elif filetype == 'HIT archive data': array = ['MSP430', 'BIN'] elif re.search('ELF',filetype): arch = e[1] if arch == 'ARM': array = ['ARM','ELF'] elif arch == 'TI msp430': array = ['MSP430','ELF'] else: pass else: pass return array def getInfo(self): """Write information about the binary to stdout.""" print("\n---------------------------------") print("Info found about the binary file submitted for upload:") print("Name: %s" % self.name) print("Path: %s" % self.path) print("Complete path to file: %s" % self.abspath()) print("Arch: %s" % self.arch) print("File type: %s" % self.filetype) print("Board: %s\n" % self.board) print("---------------------------------") return True #<EOF>
3dcc3737c0181da9e03220133464cf926229f5cf
kashifusmani/interview_prep
/arrays/webpage.py
1,709
3.53125
4
class BrowserHistory: def __init__(self, homepage: str): self.homepage = homepage self.history = [homepage] self.current_index = 0 print(self.history) print(self.current_index) def visit(self, url: str) -> None: if self.current_index +1 < len(self.history): for i in range(self.current_index+1, len(self.history)): del self.history[len(self.history)-1] self.history.append(url) self.current_index += 1 print(self.history) print(self.current_index) def back(self, steps: int) -> str: ind = self.current_index if steps > ind: ind = 0 else: ind = ind - steps self.current_index = ind print(self.history) print(self.current_index) return self.history[self.current_index] def forward(self, steps: int) -> str: ind = self.current_index if steps > len(self.history) -1 - ind: ind = len(self.history) - 1 else: ind = ind + steps self.current_index = ind print(self.history) print(self.current_index) return self.history[self.current_index] if __name__ == '__main__': #["forward","back","back"] #[[2],[2],[7]] # Your BrowserHistory object will be instantiated and called as such: obj = BrowserHistory("leetcode.com") obj.visit("google.com") obj.visit("facebook.com") obj.visit("youtube.com") obj.back(1) obj.back(1) obj.forward(1) obj.visit("linkedin.com") obj.forward(2) obj.back(2) obj.back(7) # obj.visit(url) # param_2 = obj.back(steps) # param_3 = obj.forward(steps)
029de1a6a99a93e8b0cf273c51675120a3bcaad6
kashifusmani/interview_prep
/recursion/reverse_string.py
213
4.125
4
def reverse(s): if len(s) == 1 or len(s) == 0: return s return s[len(s)-1] + reverse(s[0: len(s)-1]) # or return reverse(s[1:]) + s[0] if __name__ == '__main__': print(reverse('hello world'))
5c2465e7451b82309e5b5f2baf9152268d3014b7
kashifusmani/interview_prep
/arrays/water.py
2,574
3.75
4
#For every element of the array, find the maximum element on its left and maximum on its right #O(n^2) def maxWater(arr, n) : res = 0 # For every element of the array for i in range(1, n - 1) : # Find the maximum element on its left left = arr[i] for j in range(i) : left = max(left, arr[j]) # Find the maximum element on its right right = arr[i] for j in range(i + 1 , n) : right = max(right, arr[j]) # Update the maximum water res = res + (min(left, right) - arr[i]) return res #Pre compoute the max left and max right values #O(n) def findWater(arr, n): # left[i] contains height of tallest bar to the # left of i'th bar including itself left = [0]*n # Right [i] contains height of tallest bar to # the right of ith bar including itself right = [0]*n # Initialize result water = 0 # Fill left array left[0] = arr[0] for i in range( 1, n): left[i] = max(left[i-1], arr[i]) # Fill right array right[n-1] = arr[n-1] for i in range(n-2, -1, -1): right[i] = max(right[i + 1], arr[i]) # Calculate the accumulated water element by element # consider the amount of water on i'th bar, the # amount of water accumulated on this particular # bar will be equal to min(left[i], right[i]) - arr[i] . for i in range(0, n): water += min(left[i], right[i]) - arr[i] return water # Python program to find # maximum amount of water that can # be trapped within given set of bars. # Space Complexity : O(1) def findWater_2(arr, n): # initialize output result = 0 # maximum element on left and right left_max = 0 right_max = 0 # indices to traverse the array lo = 0 hi = n-1 while(lo <= hi): if(arr[lo] < arr[hi]): if(arr[lo] > left_max): # update max in left left_max = arr[lo] else: # water on curr element = max - curr result += left_max - arr[lo] lo+= 1 else: if(arr[hi] > right_max): # update right maximum right_max = arr[hi] else: result += right_max - arr[hi] hi-= 1 return result # This code is contributed # by Anant Agarwal. # Driver code if __name__ == "__main__" : arr = [4, 1, 1, 2, 1, 1, 3, 1, 1, 1, 1] #arr = [2, 1, 3, 1, 1, 0, 3] n = len(arr) print(findWater_2(arr, n))
03ed32a0404db3acf09a90702a8aebd037feeca9
kashifusmani/interview_prep
/stack_queues_deques/parenthesis.py
1,033
3.90625
4
def is_balanaced(input): s = [] for item in input: if item == '(' or item == '{' or item == '[': s.append(item) else: if len(s) == 0: return False popped = s.pop() if item == '}' and not popped == '{': return False elif item == ')' and not popped == '(': return False elif item == ']' and not popped == '[': return False return len(s) == 0 def balance_check(input): if len(input) %2 != 0: return False opening = set('({[') matches = set([('(',')'),('[',']'),('{','}')]) stack = [] for item in input: if item in opening: stack.append(item) else: if len(stack) == 0: return False prev_open = stack.pop() if (prev_open, item) not in matches: return False return len(stack) == 0 if __name__ == '__main__': print(is_balanaced('()(){]}'))
09a14e49b6bb2b7944bc5ec177586a40761ca6f7
kashifusmani/interview_prep
/fahecom/interview.py
2,489
4.125
4
""" Write Python code to find 3 words that occur together most often? Given input: There is the variable input that contains words separated by a space. The task is to find out the three words that occur together most often (order does not matter) input = "cats milk jump bill jump milk cats dog cats jump milk" """ from collections import defaultdict def algo(input, words_len=3): result = {} if len(input) < words_len: pass if len(input) == words_len: result = {make_key(input): 1} else: start = 0 while start+words_len < len(input): current_set = sorted(input[start:start+words_len]) our_key = make_key(current_set) if our_key in result: start += 1 continue else: result[our_key] = 1 print(current_set) inner_start = start + 1 while inner_start+words_len < len(input): observation_set = sorted(input[inner_start:inner_start+ words_len]) if current_set == observation_set: check(our_key, result) inner_start += 1 observation_set = sorted(input[inner_start:]) if current_set == observation_set: check(our_key, result) start += 1 return result def make_key(input): return ','.join(input) def check(our_key, result): if our_key in result: result[our_key] += 1 else: result[our_key] = 1 if __name__ == '__main__': input = "cats milk jump bill jump milk cats dog cats jump milk" print(algo(input.split(" "))) # Difference between tuple and list # What is a generator and why is it efficient # What is a decorator, how it works. # select player_id, min(event_date) as first_login from activity group by player_id order by player_id asc # with x as (select count(*) as total_logins, month-year(login_date) as month_year from logins group by month_year order by month_year asc), # with y as (select total_logins, month_year, row_number() as row), # select month_year, (b.total_logins - a.total_logins)/a.total_logins from # ( select total_logins, month_year, row from y) as a, ( select total_logins, month_year, row from y) as b where a.row + 1 = b.row # # with x as (select count(*) as num_direct_report, manager_id from employee group by manager_id where num_direct_report >=5) # select name from employee join x on employee.id=x.manager_id
14d1c9d1f4bba9b474b432e180cf7a2f1ae13487
ducanh4531/Think-like-CS
/chapter_3_1.py
5,561
4.5
4
"""first line.""" import turtle """ I. Write a program that prints We like Python's turtles! 100 times for i in range (100): print("We like Python's turtles!") """ # II. Answer a question on runestone # III. Write a program that uses a for loop to print each line is a mon- # th of year """ choosing a list or a tuple to make repeat a fixed number of times in f- or loop month_tuple = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] for month in month_tuple: print("One of the months of the year is", month) """ # IV. Assume you have a list of numbers 12, 10, 32, 3, 66, 17, 42, 99, # 20 # a. Write a loop that prints each of the numbers on a new line. """ list_number = [12, 10, 32, 3, 66, 17, 42, 99, 20] for number in list_number: print(number) # b. Write a loop that prints each of the numbers and its square on a new line #for number in list_number: print("number in list number " + str(number) + ", its square is", \ number ** 2) """ # V. Use for loops to make a turtle draw these regular polygons # (regular means all sides the same lengths, all angles the same): """ window = turtle.Screen() anton = turtle.Turtle() anton.shape("blank") anton.fillcolor("blue") anton.begin_fill() # An equilateral triangle for i in range(3): anton.forward(150) anton.left(120) # A square for i in range(4): anton.forward(150) anton.left(90) # A hexagon (six sides) for i in range(6): anton.forward(150) anton.left(60) # An octagon (eight sides) for i in range(8): anton.forward(-100) anton.right(180 - 135) anton.end_fill() window.exitonclick() """ # VI. Write a program that asks the user for the number of sides, the # length of the side, the color, and the fill color of a regular # polygon. The program should draw the polygon and then fill it in """ numb_of_sides = int(input("Enter number of sides you want: ")) len_of_side = int(input("Enter the length of the side you want: ")) col = input("Enter your color: ") fill_col = input("Enter your fill color: ") window = turtle.Screen() anton = turtle.Turtle() anton.color(col) anton.fillcolor(fill_col) anton.shape("blank") anton.begin_fill() for i in range(numb_of_sides): anton.forward(len_of_side) anton.right(360 / numb_of_sides) anton.end_fill() """ # VII. Make a program with a list of data that depict random turn each # 100 steps forward (Positive angle are counter-clockwise) """ window = turtle.Screen() pirate = turtle.Turtle() rand_turn = [160, -43, 270, -97, -43, 200, -940, 17, -86] for move in rand_turn: pirate.left(move) pirate.forward(100) print(pirate.heading()) window.exitonclick() """ # IX. Write a program to draw a star with 5 peaks: """ window = turtle.Screen() anton = turtle.Turtle() anton.shape("blank") anton.pensize(3) for i in range(5): anton.forward(150) anton.right(180 - 36) window.exitonclick() """ # X. Write a program to draw a face of a clock which use turtle shape # to indicate each number """ window = turtle.Screen() clock = turtle.Turtle() window.bgcolor("lightgreen") clock.shape("turtle") clock.color("blue") clock.pensize(2) clock.up() for i in range(12): clock.forward(70) clock.down() clock.forward(10) clock.penup() clock.forward(20) clock.stamp() clock.backward(100) clock.right(30) window.exitonclick() """ # XI. Write a program to draw some kind of picture # Create a snow flower with turtle module """ window = turtle.Screen() snow = turtle.Turtle() snow.speed(0) window.bgcolor("mediumslateblue") snow.fillcolor("deepskyblue") snow.color("deepskyblue") snow.pensize(3) snow.begin_fill() for i in range(6): for i in [21, 15, 10, 5]: snow.forward(8) snow.left(60) snow.forward(i) if i == 21: snow.forward(3) snow.right(30) snow.forward(5) snow.stamp() snow.forward(-5) snow.left(30) snow.forward(-3) snow.forward(-i) snow.right(120) snow.forward(i) snow.forward(-i) snow.left(60) snow.forward(10) snow.stamp() snow.forward(-42) snow.right(60) snow.forward(15) snow.right(120) snow.forward(15) snow.left(120) # too long snow.forward(8) snow.left(60) snow.forward(21) snow.forward(-21) snow.right(120) snow.forward(21) snow.forward(-21) snow.left(60) snow.forward(8) snow.left(60) snow.forward(15) snow.forward(-15) snow.right(120) snow.forward(15) snow.forward(-15) snow.left(60) snow.forward(8) snow.left(60) snow.forward(10) snow.forward(-10) snow.right(120) snow.forward(10) snow.forward(-10) snow.left(60) snow.forward(8) snow.left(60) snow.forward(5) snow.forward(-5) snow.right(120) snow.forward(5) snow.forward(-5) snow.left(60) snow.forward(10) snow.stamp() snow.forward(-42) snow.end_fill() window.exitonclick() """ # XII. Assign a turtle to a variable and print its type """ window = turtle.Screen() anton = turtle.Turtle() print(type(anton)) """ # XIII. Create a spider with n legs coming out from a center point. The # each leg is 360 / n degrees legs = int(input("Enter your spider legs: ")) window = turtle.Screen() spider = turtle.Turtle() spider.pensize(2) for i in range(legs): spider.forward(30) spider.forward(-30) spider.right(360 / legs) window.exitonclick()
33ab41836352c8c68c6931db4c415aa2425932e7
emnak/boilerplate-
/src/data_generators/keras_dataset_generator.py
3,252
3.734375
4
import pandas as pd from keras_preprocessing.image import ImageDataGenerator from tensorflow.keras import datasets from tensorflow.keras.utils import Sequence, to_categorical class KerasDatasetGenerator(Sequence): """ Generates images batches from a Keras dataset, for the chosen subset ('training', 'validation' or 'test'). """ def __init__( self, dataset_name, batch_size, shuffle=True, subset="training", validation_split=0.3, data_augmentation=None, ): """ Args: dataset_name (str): a dataset that can be downloaded with Keras. The list of available datasets is here: https://keras.io/datasets/ batch_size (int): number of images per batch. shuffle (bool): whether to shuffle the data (default: True) subset (str): 'training', 'validation' or 'test'. Keras datasets are already split into 'train' and 'test', and here: - 'training' corresponds to a subset of Keras 'train' set, determined by 'validation_split'. - 'validation' corresponds to the other subset of Keras 'train' set - 'test' exactly corresponds to Keras 'test' set validation_split (float): how to split Keras 'train' set into 'training' and 'validation' subsets. - 'training' set will be images: validation_split * len(train set) -> len(train set) - 'validation' set will be images: 0 -> validation_split * len(train set) data_augmentation (dict): parameters to be passed to Keras ImageDataGenerator to randomly augment images. """ if subset not in ["training", "validation", "test"]: raise ValueError("subset should be 'training', 'validation' or 'test'") self._batch_size = batch_size dataset = getattr(datasets, dataset_name) (x_train_val, y_train_val), (x_test, y_test) = dataset.load_data() x_subset, y_subset = ( (x_test, y_test) if subset == "test" else (x_train_val, y_train_val) ) if len(x_subset.shape) == 3: x_subset = x_subset.reshape(x_subset.shape + (1,)) self._input_shape = x_subset[0].shape self._num_classes = len(pd.np.unique(y_subset)) y_subset = to_categorical(y_subset, self._num_classes) self._iterator = ImageDataGenerator( validation_split=validation_split, rescale=1 / 255, **data_augmentation or {} ).flow( x_subset, y_subset, batch_size=batch_size, shuffle=shuffle, **{"subset": subset} if subset != "test" else {} ) self._annotations_df = pd.DataFrame( {"label_true": self._iterator.y.argmax(axis=1)} ) def __len__(self): return len(self._iterator) def __getitem__(self, index): return self._iterator[index] @property def input_shape(self): return self._input_shape @property def num_classes(self): return self._num_classes @property def annotations_df(self): return self._annotations_df
fc3ed7d7ae3a68288d07d2b1f56bd9fffda03264
ELLIPSIS009/100-Days-Coding-Challenge
/Day_3/Save_Konoha/save_kohona.py
1,794
3.71875
4
''' Problem :- Save Konoha (SAVKONO) Platform :- Codechef Link :- https://www.codechef.com/problems/SAVKONO Problem statement :- Pain is the leader of a secret organization whose goal is to destroy the leaf village(Konoha). After successive failures, the leader has himself appeared for the job. Naruto is the head of the village but he is not in a condition to fight so the future of the village depends on the soldiers who have sworn to obey Naruto till death. Naruto is a strong leader who loves his villagers more than anything but tactics is not his strong area. He is confused whether they should confront Pain or evacuate the villagers including the soldiers (he loves his villagers more than the village). Since you are his advisor and most trusted friend, Naruto wants you to take the decision. Pain has a strength of Z and is confident that he will succeed. Naruto has N soldiers under his command numbered 1 through N. Power of i-th soldier is denoted by Ai. When a soldier attacks pain, his strength gets reduced by the corresponding power of the soldier. However, every action has a reaction so the power of the soldier also gets halved i.e. Ai changes to [Ai/2]. Each soldier may attack any number of times (including 0). Pain is defeated if his strength is reduced to 0 or less. Find the minimum number of times the soldiers need to attack so that the village is saved. Example : Input: 1 5 25 7 13 8 17 3 Output: 2 ''' count = int(input()) for i in range(count): n, z = list(map(int, input().split(' '))) a = list(map(int, input().split(' '))) counter = 0 while z > 0: attack = max(a) z -= attack a[a.index(attack)] = a[a.index(attack)] / 2 counter += 1 if counter == 0: print('Evacuate') else: print(counter)
3955d791f137b973ad49f5cf928d4da1ce8562a3
ELLIPSIS009/100-Days-Coding-Challenge
/Day_2/Div.64/Div.64_M-2.py
954
3.625
4
''' Question code :- 887A Platform :- Codeforces Link :- https://codeforces.com/contest/1446/problem/A Problem statement :- Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system. Example 1: input : 100010001 output : yes Example 2: input : 100 output : no ''' def cal(a): oneFound = False zeroCount = 0 for i in a: if oneFound: if i == '0': zeroCount += 1 else: if i == '1': oneFound = True if oneFound: if zeroCount >= 6: return 'yes' else: return 'no' else: return 'no' a = input() print(cal(a))
3302c9a22c0131ba10cca6acfaf7182aca246b54
danhigham/advent_of_code
/2/run.py
901
3.515625
4
import re f = open("./2/input.txt") raw_data = f.read().split("\n") first_valid_count = 0 second_valid_count = 0 for x in raw_data: if (x.strip()==""): continue value = re.search(':\s([a-z]*)', x).group(1) minOcc = int(re.search('^(\d*)-', x).group(1)) maxOcc = int(re.search('^\d*-(\d*)\s', x).group(1)) letter = re.search('^\d*-\d*\s([a-z])', x).group(1) firstPos = minOcc secondPos = maxOcc occCount = value.count(letter) if (occCount >= minOcc and occCount <= maxOcc): first_valid_count = first_valid_count + 1 print(value[firstPos-1] + " " + letter) if (value[firstPos-1] == letter and value[secondPos-1] == letter): continue if (value[firstPos-1] == letter or value[secondPos-1] == letter): second_valid_count = second_valid_count + 1 print(first_valid_count) print(second_valid_count) print(len(raw_data))
0cb94a6782ceed0709216733f95d1581c5ebc821
ao9000/tic-tac-toe-ai
/run_game.py
7,054
3.796875
4
""" Pygame based version of tic-tac-toe with minimax algorithm artificial intelligence (AI) game """ # UI imports import pygame import sys from game_interface.color import color_to_rgb from game_interface.templates import game_board, selection_screen, board_information, highlight_win # Game logic imports import random from game.board import create_board, win_check, is_board_full, get_turn_number from game_interface.helper_functions import bot_move_input_handler, human_move_input_handler, record_draw, record_win, human_input_selection_screen_handler # Define screen size width, height = 600, 600 def setup_game(): """ Setup the pygame game window and tick rate properties :return: type: tuple Contains the pygame.surface and pygame.clock objects for the game pygame.surface class is responsible for the the window properties such as the dimension and caption settings pygame.clock class is responsible for the frame per second (fps) or tick rate of the game """ # Initialize module pygame.init() # Define screen dimensions screen_size = (width, height) screen = pygame.display.set_mode(screen_size) # Define game window caption pygame.display.set_caption("Tic Tac Toe") # Define game clock clock = pygame.time.Clock() return screen, clock def render_items_to_screen(screen, interface_items): """ Renders all the items in interface_items dictionary to the screen :param screen: type: pygame.surface The surface/screen of the game for displaying purposes :param interface_items: type: dict Dictionary containing all of the user interface (UI) items to be displayed """ # List to exclude rendering exclude_list = [ 'game_board_rects' ] for key, value in interface_items.items(): if key not in exclude_list: if isinstance(value, list): for move in value: if move: move.draw_to_screen(screen) else: value.draw_to_screen(screen) def post_game_delay(): """ Forces the screen to update while adding a delay and clearing any events that were added during the delay. Used for adding a delay between multiple tic-tac-toe games. This is to provide time for the player to react to what is happening in the game. """ # Refresh screen & add delay pygame.display.update() # Caution, when wait is active, event gets stored in a queue waiting to be executed. # This causes some visual input lag. Must clear the event queue after done with pygame.time.wait pygame.time.wait(2000) pygame.event.clear() def main(): """ The main function of the game. Responsible for the setup of game window properties, creating players, scheduling scenes in the game, recording player statistics and looping the game. """ # Setup game screen, clock = setup_game() # Create list of players players = [] # Define whose turn player = None # Define stats recording records = { # Record turn number 'turn_num': 0, # Record bot wins 'bot_win': 0, # Record human wins 'human_win': 0, # Record draws 'draw': 0 } # Define screen states intro = True game = True # Create a blank Tic Tac Toe board board = create_board() # Game loop while True: # tick rate clock.tick(30) mouse_position = pygame.mouse.get_pos() mouse_clicked = False for event in pygame.event.get(): # Break loop if window is closed if event.type == pygame.QUIT: pygame.quit() sys.exit() # Break loop if ESC key is pressed elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_clicked = True # White background/clear previous objects screen.fill(color_to_rgb("white")) if intro: # Draw selection screen interface_items = selection_screen(screen, mouse_position) render_items_to_screen(screen, interface_items) # Handle user input if mouse_clicked: human_input_selection_screen_handler(interface_items, players, mouse_position) # Proceed to next screen if user selected a choice & assign players if players: # Unpack players bot, human = players[0], players[1] # Random starting player player = random.choice(players) # Move on to game screen intro = False elif game: # Game scene # Draw board information interface_items = board_information(screen, records) render_items_to_screen(screen, interface_items) # Draw tic tac toe board interface_items = game_board(screen, board, players) render_items_to_screen(screen, interface_items) # Check if game is finished if win_check(board): # Game is finished # Highlight the winning row interface_items = highlight_win(interface_items, board) render_items_to_screen(screen, interface_items) # Add delay post_game_delay() # Record stats record_win(player, records) # Reset board board = create_board() # Next game, random starting turn again player = random.choice(players) elif is_board_full(board): # Game is finished # Add delay post_game_delay() # Record stats record_draw(records) # Reset board board = create_board() # Next game, random starting turn again player = random.choice(players) else: # Game not finished # Make a move (bot/human) if player.bot: # Bot turn bot_move_input_handler(board, bot) else: if mouse_clicked: # Human turn human_move_input_handler(board, interface_items, mouse_position, human) # Cycle turns if get_turn_number(board) != records["turn_num"]: if not win_check(board) and not is_board_full(board): # Subsequent turns player = human if player.bot else bot records["turn_num"] = get_turn_number(board) # Update screen pygame.display.update() if __name__ == '__main__': main()
56ea49400b82ee1982b4103e4f34c9bee7b5e650
mekdeshub123/cap_lab_5
/five_days_forcast.py
1,191
3.59375
4
#the data request is limited to USA cities only import os import requests from datetime import datetime #retrieve key that stored in envromental variable key = os.environ.get('WEATHER_KEY') #print(key) print('----------------------------------------------') print('\nTHE DATA REQUEST IS LIMITED TO US CITIES ONLY') print('----------------------------------------------\n') city_name = input('Enter city: ')#user imputs for the name parameter city = city_name + ', us'# concatnates the user imput with value, us. query = {'q': city, 'units': 'imperial', 'appid':key}#parameter in query url = 'http://api.openweathermap.org/data/2.5/forecast' try: data = requests.get(url, params=query).json()# Fetch data using get method and put it into json file print(data) forecast_items = data['list']#storing data into list print('\n') for forecast in forecast_items:#loop through the list timestamp = forecast['dt'] date =datetime.fromtimestamp(timestamp)#convert to a readable date and time format temp = forecast['main']['temp'] print(f'at {date}temprature is {temp}')# put it to format string except: print('city cannot be found!')
b1da56330aaed2070bd2a2cf71e7905f800f11db
LaytonAvery/DigitalCraftsWeek1
/Day4/todolist.py
1,089
4.21875
4
choice = "" task = {} def add_task(choice): task = [{"title": name, "priority": priority}] task.append("") for key, value in task.append(""): print(key, value) # print(task) def delete_task(choice): del task def view_all(): for key, value in task.items(): print(key, value) choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) while True: choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) if choice == "1": name = input("Enter a task: ") priority = input("Enter task priority: ") add_task(choice) elif choice == "2": for items in task(): print(items) deletion = input("What would you like deleted? ") delete_task(choice) elif choice == "3": view_all() elif choice == "q": break
00aec8932d5749f9f5af478ebb9dbeff183a5c11
krizo/checkio
/quests/singleton.py
874
4.125
4
''' https://py.checkio.org/en/mission/capital-city/ You are an active traveler who have visited a lot of countries. The main city in the every country is its capital and each country can have only one capital city. So your task is to create the class Capital which has some special properties: the first created instance of this class will be unique and single, and all of the other instances should be the same as the very first one. Also you should add the name() method which returns the name of the capital. In this mission you should use the Singleton design pattern. ''' class Capital(object): __instance = None def __new__(cls, city): if Capital.__instance is None: Capital.__instance = object.__new__(cls) Capital.__instance.city = city return Capital.__instance def name(self): return self.city
a4267b4bc3cc1901c8f717b192af77f9feec37b3
yinglingwang07238422/csv2txt
/csv2txt/cmd.py
1,080
3.734375
4
#!/usr/bin/env python # encoding=utf-8 import os import argparse import csv2txt def convert_by_cmd(): # 参数定义 parser = argparse.ArgumentParser(description="Convert a csv file to token separator txt file") parser.add_argument('--version', '-v', action='version', version='%(prog)s version : v'+csv2txt.getVersion(), help='show the version') parser.add_argument('--separator', '-s', metavar='"\\t"', default= "\t", help='The separator between column, default is TAB(\\t)') parser.add_argument("csv", type=argparse.FileType('r'), help='input csv file path to convert') parser.add_argument("txt", type=argparse.FileType('w'), help='ouput txt file path') # 解析参数 args = parser.parse_args() csvPath=os.path.abspath(args.csv.name) txtPath=os.path.abspath(args.txt.name) separator=csv2txt.escapeSeparatorFlipDict.get(args.separator, args.separator); escapeSeparator= csv2txt.escapeSeparator(separator); print(u'Convert '+csvPath+' to ' +txtPath+ ' with separator '+ escapeSeparator) # 执行转换 csv2txt.convertByFile(args.csv, args.txt, separator);
ef657e61a2dfdac5e44aaa1187aa11c6f6713017
niraj36/test
/fizz_buzz.py
410
3.75
4
def fizz_buzz(start_value, end_value, fizz_value, buzz_value): count = start_value message = count while count <= end_value: if count % fizz_value == 0: message = 'Fizz' if count % buzz_value == 0: message += ' Buzz' elif count % buzz_value == 0: message = 'Buzz' print(message) count += 1 message = count
d8f3097c5b0dc01d85ee0b72006d1fdb8b6431e1
VioletM/student-python-graphics
/1.py
744
4
4
from tkinter import * ## Размеры холста: W = 600 # ширина H = 400 # высота ## Диаметр мячика: D = 10 ## Начальное положение мячика: X_START = 150 Y_START = 100 Win=Tk() c = Canvas(Win, width=W, height=H, bg='black') c.pack() ## Отрисовка поля: c.create_rectangle(30, 30, W - 30, H - 30, outline='white', width=8) c.create_line(W / 2, 30, W / 2, H - 30, fill='white', width=8, dash=(100, 10)) ## Ракетки и мячик: c.create_rectangle(X_START, Y_START, X_START + D, Y_START + D, fill='red') c.create_line(50, 150, 50, 200, fill='white', width=10) c.create_line(W - 50, 150, W - 50, 200, fill='white', width=10) Win.mainloop()
96d924eb36cf0b3e23c5a71d555ee6cd24970c11
Ola752/load-shed
/loadshed/utils/timing.py
2,509
4.03125
4
import timeit import datetime start_time = 0 lap_time = 0 # level 1 lap_time2 = 0 # level 2 def start(): """ Start timing :return: nothing """ global start_time global lap_time global lap_time2 start_time = lap_time = lap_time2 = timeit.default_timer() time_now = datetime.datetime.now() print(f'Started at {time_now.strftime("%I:%M%p")}') def lap(is_print_out=False): """ Calc the elapsed time from the previous lap (i.e. lap_time). :return: int """ global lap_time current_time = timeit.default_timer() s_out = time2str(current_time - lap_time) lap_time = current_time if is_print_out: print(s_out) return s_out def lap2(is_print_out=False): """ Calc the elapsed time from the previous lap (i.e. lap_time). :return: int """ global lap_time2 current_time = timeit.default_timer() s_out = time2str(current_time - lap_time2) lap_time2 = current_time if is_print_out: print(s_out) return s_out def stop(is_print_out=True): """ Print out the elapsed time from the start time (i.e. start_time). :return: nothing """ global start_time current_time = timeit.default_timer() time_now = datetime.datetime.now() s_out = 'Stopped at {}, total: {}'.format(time_now.strftime('%I:%M%p '), time2str(current_time - start_time)) if is_print_out: print(s_out) return s_out def stop_full(is_print_out=False): """ Print out the elapsed time from the start time (i.e. start_time). :return: nothing """ global start_time current_time = timeit.default_timer() time_now = datetime.datetime.now() s_out = 'Stopped at {} in {}'.format(time_now.strftime('%I:%M%p %d/%m/%Y'), time2str(current_time - start_time)) if is_print_out: print(s_out) return s_out def stop_inline(): """ Print out the elapsed time from the start time (i.e. start_time). :return: nothing """ global start_time current_time = timeit.default_timer() s_out = '[{}]'.format(time2str(current_time - start_time)) print(s_out) def time2str(seconds): """ Convert number of elapsed time (in seconds, a float number) to a string. :param seconds: e.g. 62.15 :return: e.g. 1m 2.15s """ if seconds < 60: s_out = '{:.2f}s'.format(seconds) else: mins = int(seconds / 60) seconds -= 60 * mins # float s_out = '{}m {:.2f}s'.format(mins, seconds) return s_out
81e3eb880ccd149f93bfe2a4bc6c48f86ad745b7
Diogo-Ferreira/astar_he_arc
/City.py
1,079
3.5625
4
""" Ferreira Venancio Diogo IA Class HE-ARC 2016 Class city """ class City(object): def __init__(self, name, x_pos, y_pos): self.name = name self.x_pos = float(x_pos) self.y_pos = float(y_pos) self.connections = {} self.gx = 0 self.parent = None def add_connection_to(self, to, distance): self.connections[to] = float(distance) def __str__(self): return self.name def __getitem__(self, item): """Allows to get the connection like: sourceCity['targetCity'] """ if item in self.connections: return self.connections[item] else: return 0 def __hash__(self): return str(self.name).__hash__() def __iter__(self): """Allows to iterate each connections""" return self.connections.items().__iter__() def __eq__(self, other): if isinstance(other, str): return self.name == other elif isinstance(other, City): return self.name == other.name else: return super.__eq__(other)
05c34a6a177cd48e5c8e1f2b05ef5413e2ec9b41
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/saymyname.py
206
3.90625
4
# ask the user for their name name = input('What is your name? ') # print their name 100 times for x in range(100): # print their name followed by a space,not a new line print(name,end = ' rules, ')
f5c9eb271fbd7da172fa9af87960faff1bd5f675
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/fibfunctions.py
267
4.15625
4
def fibonacci(num): print("printing fibonacci numbers till ", num) v = 1 v1 = 1 v2 = v + v1 print(v) print(v1) while v2 < num: print(v2) v = v1 v1 = v2 v2 = v + v1 fibonacci(10) fibonacci(20) fibonacci(500)
b85eddbab124941dcffd5c4918478fc3f9b8837b
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/Click-And-Smile.py
843
3.53125
4
# ClickAndSmile.py import random import turtle def draw_smiley(x, y): pen.penup() pen.setpos(x, y) pen.pendown() # Face pen.pencolor("yellow") pen.fillcolor("yellow") pen.begin_fill() pen.circle(50) pen.end_fill() # Left eye pen.setpos(x-15, y+60) pen.fillcolor("blue") pen.begin_fill() pen.circle(10) pen.end_fill() # Right eye pen.setpos(x+15, y+60) pen.begin_fill() pen.circle(10) pen.end_fill() # Mouth pen.setpos(x-25, y+40) pen.pencolor("black") pen.width(10) pen.goto(x-10, y+20) pen.goto(x+10, y+20) pen.goto(x+25, y+40) pen.width(1) pen = turtle.Pen() pen.speed(0) pen.hideturtle() turtle.bgcolor("black") turtle.onscreenclick(draw_smiley) turtle.getscreen()._root.mainloop()
b77b996655f2c3a53acf170a6b4b7f78fc9051ac
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/circlescolour.py
350
3.875
4
import turtle t = turtle.Pen() colours = ["red", "yellow", "blue", "green","orange", "purple", "white", "gray",'pink','light blue','brown', 'light green'] t.speed(20) for x in range(12): t.fillcolor(colours[x % colours.__sizeof__()]) t.begin_fill() t.circle(100) t.end_fill() t.left(30) turtle.textinput("Enter your name", "Done")
68e086044625f54a75bf362a4dd6d63c4632cff6
NALM98/Homework-Course-1
/HW3/HW1.py
1,689
4.125
4
print("Введите, пожалуйста,три любых числа") a = int(input()) b = int(input()) c = int(input()) #1. a и b в сумме дают c #2. a умножить на b равно c #3. a даёт остаток c при делении на b #4. c является решением линейного уравнения ax + b = 0 #5. a разделить на b равно c #6. a в степени b равно c. #1 if a+b == c: print("Сумма чисел a и b равна числу c") else: print("Сумма чисел a и b не равна числу c") #2 if a*b == c: print("Произведение чисел a и b равно числу c") else: print("Произведение чисел a и b не равно числу c") #3 if a%b == c: print ("Число a даёт остаток, равный числу c при делении на число b") else: print ("Число a не даёт остаток, равный числу c при делении на число b") #4 if -1*b/a == c: print("Число c является решением линейного уравнения ax+b") else: print("Число c не является решением линейного уравнения ax+b") #5 if a/b == c: print("Частное от деления числа a на число b равно числу c") else: print("Частное от деления числа a на число b не равно числу c") #6 if a**b == c: print("Число a в степени b равно числу с") else: print("Число a в степени b не равно числу c")
c1820b939c67c0a7587026e6434419e4f7e5667d
filipmihal/ml-coursera-python-coursework
/regression/linear.py
2,071
4.03125
4
import os from abstract import AbstractRegression import numpy as np from matplotlib import pyplot from scipy import optimize class LinearRegression(AbstractRegression): """Linear regression class""" def plot_data(self): index = 0 for feature in self.get_features().transpose(): index += 1 pyplot.plot(feature, self.labels, 'ro', ms=10, mec='k') pyplot.ylabel('labels') pyplot.xlabel('features ' + str(index)) pyplot.show() def cost_function(self, theta: np.ndarray) -> np.ndarray: """ Compute cost for linear regression. Computes the cost of using theta as the parameter for linear regression to fit the data points in X and y. :param theta :return: """ matrix = np.subtract(np.dot(self.features, theta), self.labels) J = np.dot(matrix.transpose(), matrix) / (2 * self.labels.size) return J def gradient(self, theta: np.ndarray, alpha: float) -> np.ndarray: # compute gradient for the constants # compute the rest of gradients for all features output = np.zeros(self.features.shape[1]) #add to the first row of the output k = 0 output[k] = alpha * np.sum(np.dot(self.features, theta) - self.labels) / self.labels.size for feature in self.get_features().transpose(): k += 1 output[k] = alpha * np.dot(np.dot(self.features, theta) - self.labels, feature) / self.labels.size return output def minimize_cost(self, theta: np.ndarray): # number of iterations output = optimize.minimize(self.cost_function, theta, jac=True, method='TNC', options={'maxiter': 400}) return output.x def predict(self, theta: np.ndarray): print("ahoj") data = np.loadtxt(os.path.join('../Exercise1/Data', 'ex1data1.txt'), delimiter=',') X, y = data[:, 0], data[:, 1] linear_regression = LinearRegression(X.T, y) linear_regression.plot_data() linear_regression.gradient(np.array([0, 0]), 0.01)
5e92cdb5639fdf7277da9808d00f3acddcf7c8f6
SwethaGullapalli/PythonTasks
/FolderComparision.py
1,358
3.796875
4
import os import shutil Folderpath1=raw_input("please enter first folder name : ") Folderpath2=raw_input("please enter second folder name : ") needmatchedfiles=raw_input("do you want matched files? ") needmatchedfiles=needmatchedfiles=="yes" donotneedmatchedfiles=raw_input("do you want unmatched files? ") donotneedmatchedfiles=donotneedmatchedfiles=="yes" print needmatchedfiles print donotneedmatchedfiles list1=[] list2=[] matchedlist=[] unmatchedlist=[] if os.path.isdir(Folderpath1): print "This is a folder1" Folderfiles1=os.listdir(Folderpath1) print Folderfiles1 if os.path.isdir(Folderpath2): print "This is a folder2" Folderfiles2=os.listdir(Folderpath2) print Folderfiles2 for Filename1 in Folderfiles1: if os.path.isfile(Folderpath1 +'\\'+ Filename1): list1.append(Filename1) for Filename2 in Folderfiles2: if os.path.isfile(Folderpath2 + "\\"+ Filename2): list2.append(Filename2) for i in list1:#a.txt,b.txt for j in list2:#c.txt,d.txt,a.txt if needmatchedfiles: if i==j: matchedlist.append(i) else: if i not in unmatchedlist : unmatchedlist.append(i) if j not in unmatchedlist : unmatchedlist.append(j) if needmatchedfiles: print "List is Matched and the matched list is %s"%matchedlist if donotneedmatchedfiles: print"List is not matched and the unmatched list is %s"%unmatchedlist
2c4041af39e9c050adb9f1aa6352a6b9c25c8436
SwethaGullapalli/PythonTasks
/PrintFileNameHavingPy.py
866
4.375
4
#program to print the file extension having py """give input as list of file names iterate each file name in file names list declare one variable for holding file extension declare variables for index and dot index iterate each character in the file name increment the index by 1 if Character is equal to "." assign index to dot index if index is greater than or equal to dot index concatenate the character to file extension variable if .py== file extension variable print file name""" FileNameList = ["blue.py","black.txt","orange.log","red.py"] for FileName in FileNameList: FileExtension="" Index =0 DotIndex = -1 for Character in FileName: if Character == ".": DotIndex = Index if Index>=DotIndex and DotIndex!=-1: FileExtension=FileExtension+Character Index+=1 if".py" == FileExtension: print FileName
a3649f42792c2945eccc395db2b53e2a5beeaec1
berkio3x/pyray3d
/vector.py
1,451
3.5
4
import math class Vec3: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __str__(self): return f'Vec3({self.x},{self.y},{self.z})' def __sub__(self, other): return Vec3(self.x - other.x , self.y - other.y , self.z - other.z) def __add__(self, other): return Vec3(self.x + other.x , self.y + other.y , self.z + other.z) def mag(self): return math.sqrt(self.x**2 + self.y**2 + self.z**2) def __div__(self, other): return Vec3(self.x/other, self.y/other , self.z/other) def __rmul__(self, other): return Vec3(self.x*other, self.y*other , self.z*other) def __mul__(self, other): return Vec3(self.x*other, self.y*other , self.z*other) def __neg__(self,other): return Vec3(-1*self.x, -1*self.y, -1*self.z) def __truediv__(self, other): return Vec3(self.x/other, self.y/other , self.z/other) def dot(self, other): if isinstance(other, Vec3): return self.x * other.x + self.y * other.y + self.z * other.z raise Exception('this should recieve an arfument of type Vec3') def cross(self, other): if isinstance(other, Vec3): return Vec3( self.y* other.z - self.x* other.y, self.z* other.x - self.x* other.z , self.x * self.y - self.y * self.x) raise Exception('this should recieve an arfument of type Vec3')
51b40c1df3d52d3b1089dc01438022dbd506133c
stevenhvtran/Maze-Generator
/listMaze.py
6,337
3.78125
4
from pprint import pprint import random import numpy as np #Generates the grid needed to start a maze def gridGen(x): if x%2 != 0: #Creates the grid being used grid = [[0 for i in range(0,x)] for i in range(0,x)] grid = walls(walls(grid, x), x) return(list(map(list, grid))) else: #Forces an odd number for dimensions of grid gridGen(x+1) #Creates the walls of the maze def walls(grid, x): grid[::2] = [[i+1 for i in grid[i]] for i in range(0,int((x+1)/2))] grid = list(zip(*grid)) return grid #Sets the starting point of the maze to a random co-ordinate on the edge of the grid def start(grid): randCoord = [1, 2*random.randint(0, (len(grid)-3)/2)+1] #Randomizing a point in first row grid[0][randCoord[1]] = 4 #Sets starting point to 3 grid[1][randCoord[1]] = 3 #Sets predetermined first step to 3 too #Randomly reflects grid across diagonal to change starting edge if random.getrandbits(1) == 0: grid = transpose(grid) randCoord = transposeC(randCoord) #Randomly reflects the grid across the horizontal to change starting edge if random.getrandbits(1) == 0: grid = reverse(grid) randCoord = reverseC(randCoord, grid) return [grid, randCoord] #Reflects a square array across its diagonal (top left to bottom right) def transpose(grid): return list(map(list, zip(*grid))) #Changes co-ordinate of a point on a transposed array to match transformation def transposeC(coord): return [coord[1], coord[0]] #Reflects an array across its horizontal def reverse(grid): return grid[::-1] #Changes co-ordinate of a point on a reflected array to match transformation def reverseC(coord, grid): return [len(grid) - 1 - coord[0], coord[1]] #Picks a random direction for the maze's path to go on def goto(grid, invDir, squigFactor): #Picks directions that aren't already flagged as being 'invalid' previously direction = random.choice([dir for dir in ['n','s','e','w'] if dir not in invDir]) #Direction randomizer length = random.randint(0, int(np.sqrt(len(grid))/squigFactor))*2 return [length, direction] #Checks to see if path is clear and if so, moves current position to a new one as determined #by goto function def go(pos, grid, length, direction): #Moves the current position to the new place turning all those in path to 3's global invDir ''' Creates the path For every input from the goto randomizer... Transform the grid so that Easterly movement on the transformed grid is equivalent to the input direction. Then move the path to the east in accordance to goto randomizer if path is valid, if not add compass direction to invDir list. Then transform the grid back to its original form and return the grid and the new active co-ordinate. ''' if direction == 'n': grid = transpose(reverse(grid)) pos = transposeC(reverseC(pos, grid)) if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('n') grid = reverse(transpose(grid)) pos = reverseC(transposeC(pos), grid) if direction == 'e': if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('e') if direction == 's': grid = transpose(grid) pos = transposeC(pos) if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('s') grid = transpose(grid) pos = transposeC(pos) if direction == 'w': grid = transpose(reverse(transpose(grid))) pos = transposeC(reverseC(transposeC(pos), grid)) if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('w') grid = transpose(reverse(transpose(grid))) pos = transposeC(reverseC(transposeC(pos), grid)) return [grid, pos, invDir] def isClear(grid, pos, length): global invDir if sum(grid[pos[0]][pos[1]:pos[1]+length+1]) == (length/2)+3 and pos[1]+length < len(grid): invDir = [] return True else: return False invDir = [] def mazeGen(x): global invDir result = start(gridGen(x)) grid, pos = result[0], result[1] hist = [] return createPath(x, grid, pos, hist) def createPath(x, grid, pos, hist): global invDir #6-2 is best configuration so far for speed and no gaps squigFactor = 6 #Medium effect on time, increasing will increase density of maze and reduce gaps retries = 2 #IDK effect on time but increasing value decreases black gaps while True: for i in range(0, 8): #Optimally only needs to loop 4 times to get all compass directions #If all moves in every direction are invalid retries with smaller path #Breaks after all retries are used up if len(invDir) == 4: invDir = [] if retries > 0: retries -= 1 continue if retries == 0: retries += 2 #SHOULD BE THE SAME AS RETRIES STARTING VALUE hist.remove(pos) if len(hist) < 2: break pos = random.choice(hist) step = goto(grid, invDir, squigFactor) grid, pos, invDir = go(pos, grid, step[0], step[1]) if pos not in hist: hist.append(pos) invDir = [] if len(hist) < 2: break #Re-use the start function to pick an endpoint for the maze return start(grid)[0]
3cd1af446a478f64466a9761c16b7f4d21b834d7
tonyw0527/Python-algorithm-notes
/Implementation/combinationsAndPrimeNumber.py
609
3.828125
4
# 리스트C3 의 조합의 경우의 수를 담은 리스트를 얻는다. # 각 원소의 합이 소수인 것들의 수만 더한다. from itertools import combinations from math import sqrt def isPrime(num): if num < 2: return False for n in range(2, int(sqrt(num)) + 1): if num % n == 0: return False return True def solution(nums): answer = 0 cases = list(combinations(nums, 3)) for c in cases: summedNum = sum(c) if isPrime(summedNum): print(summedNum, ' is prime number') answer += 1 return answer
2d9d781b6bc8ccb022ce86d4ed6f58fadcd2788b
paulan94/CTCIPaul
/4_8_find_common_ancs.py
793
3.890625
4
class Node(): def __init__(self,val): self.val = val self.right = None self.left = None def node_exists(root,node): if root == node: return True if not root: return None else: return node_exists(root.left,node) or node_exists(root.right,node) return False def find_ca(root,A,B): if not root: return None if not A and not B: return root if (node_exists(root.right,A) and node_exists(root.left,B)) or (node_exists(root.right,B) and node_exists(root.left,A)): return root else: return find_ca(root.left,A,B) or find_ca(root.right,A,B) root = Node(2) root.left = Node(1) root.left.left = Node(5) root.left.right = Node(6) root.right = Node(3) print (find_ca(root,root.left.left, root).val)
327c06d09a8423799688e23faeafdde1468b8ebc
paulan94/CTCIPaul
/AddOrMultiplyRuntimes.py
615
3.75
4
def addRunTimeAlgorithm(arrayA, arrayB): # O(A+B) for a in arrayA: print (a) for b in arrayB: print (b) def multiplyRunTimeAlgorithm(arrayA, arrayB): # O(AB) for a in arrayA: for b in arrayB: print (str(a) + "," + str(b)) if __name__ == "__main__": arrayA = ["a","b","c"] arrayB = [1,2,3,4] print ("Running add runtimes function!") addRunTimeAlgorithm(arrayA, arrayB) print ("End add runtimes function\nStarting multiply runtimes function!") multiplyRunTimeAlgorithm(arrayA, arrayB) print ("End multiply runtimes function!")
78d35c7dc69601404fa656ca6991b8586eb71a7f
paulan94/CTCIPaul
/get_len_arr.py
1,140
4.03125
4
# Given a list of n words, the task is to check if two same words come next to each other. # Then remove the pair and print the number of words left in the list after this pairwise # removal is done until no other pairs are present. # # Examples: # # Input : [ba bb bb bcd xy] # Output : 3 # As [bb, bb] cancel each other so, [ba bcd xy] is the new list. # # Input : [laurel hardy hardy laurel] # Output : 0 # As first both [hardy] will cancel each other. # Then the list will be [laurel, laurel] which also remove # each other. So, the final list doesn't contain any # word. #assumptions: can be more than 1 pair, new pairs can come from deletions of pairs def get_len_arr(arr): stack = [] if len(arr) <= 1: return len(arr) for ele in arr: if len(stack) == 0: stack.append(ele) else: popped = stack.pop() if ele != popped: stack.append(popped) stack.append(ele) return len(stack) a = ['laurel', 'hardy', 'hardy', 'laurel'] a2 = ['bc', 'bb', 'bb', 'bcd', 'xy'] print (get_len_arr(a)) print (get_len_arr(a2))
21cc678347d34d1ca41120c9bec17f757cbf6b06
paulan94/CTCIPaul
/4_5_validate_bst.py
483
3.734375
4
class Node(): def __init__(self, val): self.val = val self.left = None self.right = None def validate_bst(mn, mx, root): if not root: return True elif root.val < mn or root.val > mx: return False return validate_bst(mn,root.val,root.left) and validate_bst(root.val,mx,root.right) rt = Node(6) rt.left = Node(5) rt.left.right = Node(8) rt.left.left = Node(1) rt.right = Node(9) rt.right.right = Node(11) print (validate_bst(-100,100,rt))
41daacddca3128116a92c6a6bd83b0f197444c96
paulan94/CTCIPaul
/binsearch2.py
713
3.96875
4
def bin_search(arr,key,start,end): #we need to check if the end index is greater than 0 because #we need to ensure that end is within the bounds of [0:len(a)-1] if (start <= end): #mid will be start + (end-start)//2 #the first start keeps track of where our lower bound is #and we move to the right (end-start)//2 times mid = start + (end-start)//2 if (arr[mid] == key): return mid elif (arr[mid] > key): return bin_search(arr,key,start,mid-1) else: return bin_search(arr,key,mid+1,end) return -1 # 0 1 2 3 4 5 a=[2,5,7,9,11,20] print (bin_search(a,20,0,len(a)-1)) ##print (bin_search_iterative(a,9))
34e8dded051c178bc946de223e5ed459837bed4a
paulan94/CTCIPaul
/node.py
840
3.6875
4
class Node: def __init__(self,val): self.val = val self.left = None self.right = None rt = Node(5) rt.left = Node(2) rt.right = Node(6) rt.left.left = Node(1) rt.left.right = Node(3) def contains(root,node): if not root: return False if root == node: return True elif root.left == node or root.right == node: return True return contains(root.left, node) or contains(root.right, node) def lowestCommonAncestor(root, p, q): if not root: return None if p == q: return p.val if (contains(root.left,p) and contains(root.right,q)) or (contains(root.left,q) and self.contains(root.right,p)): return root.val return lowestCommonAncestor(root.left,p,q) or lowestCommonAncestor(root.right,p,q)
d9efef45642933fbdc520bac6a2e4b3785ae26dd
paulan94/CTCIPaul
/4_1_route_nodes.py
515
3.828125
4
class Node: def __init__(self,val): self.val = val self.children = [] def route_exists(a,b): if a.val == b.val: return True elif (not a and b) or (not b and a): return False else: for c in a.children: if route_exists(c,b): return True return False a = Node(5) b = Node(6) c = Node(7) d = Node(8) e = Node(10) f = Node(11) a.children += [b,c,d] d.children.append(e) print (route_exists(a,e)) print (route_exists(a,f))
cd2c876ba236ef81aaf268f832eeb2de7fa66f71
paulan94/CTCIPaul
/8_9_parens.py
398
3.515625
4
def get_parens(n): if n == 0: return [''] else: p_list = [] parens = get_parens(n-1) for each in parens: p_list.append('()' + each) p_list.append('(' + each + ')') p_list.append(each + '()') return set(p_list) print (get_parens(4)) print (get_parens(3)) print (get_parens(2)) print (get_parens(1)) print (get_parens(0))
dc71001743d53cc6ebc0488cc4e4d3bf975a7d79
paulan94/CTCIPaul
/My HackerRank Solutions/binary_tree_BST.py
953
3.953125
4
#Paul An #is this binary tree a BST? #This program creates an array based on an in-order traversal of the given Binary Tree. #It compares the sum starting at 0. 0 with 1, 2 with 3, up to n-1 with n to see if the sequence is ordered correctly. """ Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def checkBST(root): inorder_array = [] inorder_array = create_array(root, inorder_array) return parse_array(inorder_array) def create_array(node, inorder_array): if (node.left != None): create_array(node.left, inorder_array) inorder_array.append(node.data) if (node.right != None): create_array(node.right, inorder_array) return inorder_array def parse_array(inorder_array): for i in range(len(inorder_array)-1): if ((inorder_array[i] - inorder_array[i+1])!= -1): return False return True
4a80711d999e08b07361e0891f348ba6a29a3591
paulan94/CTCIPaul
/4_2_create_bst_min_height.py
719
3.703125
4
class Node(): def __init__(self,val): self.val = val self.left = None self.right = None def create_bst_min_height(arr,start, end): if not arr or len(arr) == 0 or end < start: return None else: mid = (start + end)//2 node = Node(arr[mid]) print (node.val) node.left = create_bst_min_height(arr,start,mid-1) node.right = create_bst_min_height(arr,mid+1,end) return node arr = [1,2,3] arr2 = [1,2,3,4,5,6,7,8] x1 = create_bst_min_height(arr,0,len(arr)-1) x2 = create_bst_min_height(arr2,0,len(arr2)-1) print (x1.val, x1.left.val, x1.right.val) print (x2.val, x2.left.val, x2.right.val, x2.left.left.val, x2.right.right.val )
394f3dafa486af4e54f0097d4c407d9678e48bce
alekseidrumov/HOMEWORK_PYTHON_ADVANCED_NUM_4
/1.py
893
3.875
4
def registration(): login = input("login: ") password = input("password: ") name = input('name: ') with open('file.txt','a') as f: f.write(login+' login '+password+' password '+name+' name ') def login(dict): dict = dict print(dict) login = input("login: ") password = input("password: ") if login in dict and password in dict: for key,value in dict.items(): if value == 'name': print('Hello',key) else: print("Try again!") while True: ans = int(input("Choose 1 - login, 2 - registration, 3 - exit: ")) if ans == 1: with open('file.txt','r') as f: str = f.read() list = str.split() dict = dict(zip(list[::2], list[1::2])) login(dict) elif ans == 2: registration() elif ans == 3: break
7af10a743dbf3690644d938655353f87a802c16c
JaLeeKi/data-python
/data_presenter.py
1,067
3.921875
4
# Create a new file called data_presenter.py. # Open the CupcakeInvoices.csv. open_file = open('CupcakeInvoices.csv') # Loop through all the data and print each row. for line in open_file: print(line) # Loop through all the data and print the type of cupcakes purchased. for line in open_file: values = line.split(',') print(values[2]) # Loop through all the data and print out the total for each invoice (Note: this data is not provided by the csv, you will need to calculate it. Also, keep in mind the data from the csv comes back as a string, you will need to convert it to a float. Research how to do this.). for line in open_file: values = line.split(',') quantity = int(values[3]) price = float(values[4]) total = quantity * price print(total) # Loop through all the data, and print out the total for all invoices combined. total = 0 for line in open_file: values = line.split(',') quantity = int(values[3]) price = float(values[4]) total = total + (quantity * price) print(total) # Close your open file. open_file.close()
3857e9ecf09d236e3e03425c3cfe37b29ab8ad99
AntonioGetsemani/EjercicioDePruebaRecursividad
/Ejercicio1Recursividad.py
198
3.5
4
author = 'Antonio Getsemani' def ConvertirNumero(num): if num == 0: return "" else: return str(num % 2) + ConvertirNumero(num//2) print(ConvertirNumero(8))
7bbf7e4294d9f9a4e6ee7ab9c66f73c67a7a5909
georgePopaEv/python-exercise
/Day2P.py
576
3.765625
4
bani = float(input("Cati bani ai in total? :")) # trecem suma de bani # alegem dobanda dintre 10, 12 sau 15 # vedem la cati o umprumuta sau a cata parte # Calculam cat tre sa plateasca fiecare persoana inapoi dobanda = int(input("Cat este dobanda la care imprumuti?10, 12 sau 15? ")) split = int(input("La cati oameni se imparte banca?")) back = round(bani / split * (1+dobanda/100) , 2) if (dobanda == 10) | (dobanda == 12) | (dobanda == 15): print(f"fiecare persoana trebuie sa plateasca : ${back} ") else: print("Eroare de introducere a dobanzii!")
5e687cca74958a11a30f7b38e0f148898296e314
georgePopaEv/python-exercise
/P9DAY.py
626
3.5625
4
import art print(art.logo) def maxim_from_dictionar(dictionar): max = 0 for i in dictionar: if dictionar[i] > max: max = pers[i] winner = i print(f"Castigatorul este {winner} care a licitat cu {max}") run = True pers = {} while run: name = input("Numele cu care liciteaza: ") suma = int(input("Suma = $")) pers[name] = suma again = input("Vrea cineva sa mai liciteze ? DA/NU").lower() if again == 'da': run = True # print('\n' * 50) elif again == 'nu': run = False maxim_from_dictionar(pers)
fe13a07aade0381d220e30fb2f3eb344a7f63405
saileshchauhan/PythonProgram
/DataStructure/Strings/1_WordFrequency.py
1,730
3.9375
4
''' @Author:Sailesh Chauhan @Date:2021-06-11 @Last Modified by:Sailesh Chauhan @Last Modified time:2021-06-11 @Title: Get length of string count each alphabet frequency and char replacement. ''' #Importing logConfig for error logging import logconfig import logging,re def create_word(): ''' Description: Parameters: Returns: ''' try: userValue=validation(input("You can enter any word\n")) return userValue except Exception as ex: logging.error(ex) def validation(stringValue): ''' Description: Provides validation for userinput. Parameters: stringValue it is userinput. Returns: correctString after validation. ''' try: regexName="^[a-zA-Z0-9.]{3,}[a-zA-Z]+$" if(re.match(regexName,stringValue)): return stringValue print("String Lenght must be more than 3") except Exception as ex: logging.critical(ex) def char_frequency(word): ''' Description: Parameters: Returns: ''' try: charFrequency={} for char in word: count=0 for index in range(len(word)): if(char==word[index]): count+=1 charFrequency.update({char:count}) return charFrequency except Exception as ex: logging.critical(ex) def char_replacement(word): ''' Description: Parameters: Returns: ''' try: char = word[0] word = word.replace(char, '$') word = char + word[1:] return word except Exception as ex: logging.critical(ex) word=create_word() print(char_replacement(word)) print("word frequency dictionary",char_frequency(word))
61cb6e042e6b49bf4dea1b95335989c5c66bdcd4
saileshchauhan/PythonProgram
/DataStructure/Lists/3_CopyList_RemoveDuplicates.py
1,944
3.90625
4
''' @Author:Sailesh Chauhan @Date:2021-06-10 @Last Modified by:Sailesh Chauhan @Last Modified time:2021-06-10 @Title: Copy list and remove duplicate element from list. ''' import logconfig import logging,copy def create_list(): ''' Description: Parameters: Returns: ''' try: defaultList=[] choice='' print("You can enter any value in set") while(choice.lower()!='q'): userValue=input("Enter value to add in set\n") defaultList.append(userValue) print("Do you want to add more values \nPress C to continue\nQ to stop\n") choice=input("Enter choice\n") return defaultList except Exception as ex: logging.error(ex) def copy_list(list): ''' Description: Parameters: Returns: ''' try: copyList=[] for item in list: copyList.append(item) return copyList except Exception as ex: logging.critical(ex) def deep_copy_list(list): ''' Description: Parameters: Returns: ''' try: deepCopy=copy.deepcopy(list) return deepCopy except Exception as ex: logging.critical(ex) list=create_list() print("New copy of list using For Loop ",copy_list(list)) print("New copy of list using Deep Copy method of Copy module ",deep_copy_list(list)) def remove_duplicates(list): ''' Description: Parameters: Returns: ''' try: index=0 end=len(list) while(index<end): count=index+1 while(count<end): if(list[index]==list[count]): list.remove(list[index]) end-=1 count-=1 count+=1 index+=1 return list except Exception as ex: logging.critical(ex) noDuplicateList=remove_duplicates(list) print("List after removing elements ",noDuplicateList)
af00f452c536b5503c79a34286fd1b78b91ddc8e
saileshchauhan/PythonProgram
/DataStructure/Lists/7_CommonItem_From2List.py
1,343
3.53125
4
''' @Author:Sailesh Chauhan @Date:2021-06-10 @Last Modified by:Sailesh Chauhan @Last Modified time:2021-06-10 @Title: Find out common item in both list. ''' #Importing logConfig for error logging import logconfig import logging,re def create_list(): ''' Description: Parameters: Returns: ''' try: defaultList=[] choice='' print("You can enter any value in list") while(choice.lower()!='q'): userValue=validation(input("Enter value to add in list\n")) defaultList.append(userValue) print("Do you want to add more values \nPress C to continue\nQ to stop\n") choice=input("Enter choice\n") return defaultList except Exception as ex: logging.error(ex) def validation(stringValue): ''' Description: Provides validation for userinput. Parameters: stringValue it is userinput. Returns: correctString after converting it to int validation. ''' try: regexName="^[0-9a-zA-Z]{1,}$" if(re.match(regexName,stringValue)): return (stringValue) print("Invalid Input") except Exception as ex: logging.critical(ex) setOne=set(create_list()) setTwo=set(create_list()) setOne.intersection_update(setTwo) print("The list of element common ",list(setOne))
012065e8a85e1ac86c2e563e5df3d7feab87101a
Exodus76/aoc19
/day1.py
759
4.125
4
#day 1 part 1 #find the fuel required for a module, take its mass, divide by three, round down, and subtract 2 #part1 function def fuel_required(mass): if(mass < 0): return 0 else: return (mass/3 - 2) #part2 fucntion def total_fuel(mass): total = 0 while(fuel_required(mass) >= 0): total += fuel_required(mass) mass = fuel_required(mass) return total input_file = open('input.txt','r') total_fuel_1 = 0 total_fuel_requirement = 0 list_of_masses = input_file.readlines() for i in list_of_masses: total_fuel_1 += fuel_required(int(i)) print("part1 = " + str(total_fuel_1)) for i in list_of_masses: total_fuel_requirement += total_fuel(int(i)) print("part2 = " + str(total_fuel_requirement))
e40fbf76d88da16cb8c9ab18b276cf1595aa8198
yz9527-1/1YZ
/pycharm/Practice/python 3自学/12-读取csv文件.py
626
3.765625
4
# -*-coding:UTF-8 -*- """ import csv with open(r'E:\YZ\data\data1.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: #print(row) #print(row[0]) print(row[0], row[1]) """ import csv with open(r'E:\YZ\data\data1.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') citys = [] password = [] days = [] for row in readCSV: city = row[0] paword = row[1] day = row[2] citys.append(city) password.append(paword) days.append(day) print(citys) print(password) print(days)
380f71e1a17b74229526deb208804f1707dafbb3
llubu/AI
/Project 3/BayesianNet/question3_solver.py
3,782
3.703125
4
class Question3_Solver: def __init__(self, cpt): self.cpt = cpt; self.skip1 = self.createTable1() self.skip2 = self.createTable2() ##################################### # ADD YOUR CODE HERE # Pr(x|y) = self.cpt.conditional_prob(x, y); # A word begins with "`" and ends with "`". # For example, the probability of word "ab": # Pr("ab") = \ # self.cpt.conditional_prob("a", "`") * \ # self.cpt.conditional_prob("b", "a") * \ # self.cpt.conditional_prob("`", "b"); # query example: # query: "qu--_--n"; # return "t"; def solve(self, query): """ This function solves the given querry and returns the letter which is most suitable. """ query = '`' + query + '`' # Adding string end delimiters uS = query.index('_') # index of the underscore in the query string tmp = query.split('_') #print tmp prevDash = tmp[0].count('-') # Count of dashes before the underScore afterDash = tmp[1].count('-') # Count of dashes after the underScore #print prevDash, afterDash if 0 != (uS - prevDash): leftch = query[uS-prevDash -1] # Index of valid character before leftmost dash else: leftch = query[uS-prevDash] if len(query) != (uS + afterDash): rtch = query[uS+afterDash +1] # Index of valid character after rightmost dash else: rtch = query[uS+afterDash] #print leftch, rtch leftsum = 0 # Sum of probalities for left dashes rtsum = 0 # Sum of probabilities for right dashes maxSum = -1 # Max sum for a particular letter in the loop maxChar = '?' # The character with maxSum for i in range(0, 26): if (0 == prevDash): leftsum = self.cpt.conditional_prob(chr(97+i) ,leftch) if (1 == prevDash): leftsum = self.skip1[chr(97+i), leftch] if (2 == prevDash): leftsum = self.skip2[chr(97+i), leftch] if (0 == afterDash): rtsum = self.cpt.conditional_prob(rtch, chr(97+i)) if (1 == afterDash): rtsum = self.skip1[rtch, chr(97+i)] if (2 == afterDash): rtsum = self.skip2[rtch, chr(97+i)] fiSum = leftsum*rtsum if ( maxSum < fiSum ): maxSum = fiSum maxChar = chr(97+i) return maxChar; def createTable1(self): """ Creates the lookup table to help eliminate hidden var 1 """ table= dict() for i in range(0,27): prev = chr(96+i) for j in range(0, 27): sum = 0 cur = chr(96+j) for k in range(0, 27): sum += self.cpt.conditional_prob(chr(96+k), prev) * self.cpt.conditional_prob(cur, chr(96+k)) table[prev,cur] = sum return table def createTable2(self): """ Creates the lookup table to help eliminate hidden var 2 """ table = dict() for i in range(0, 27): prev = chr(96+i) for j in range(0, 27): sum = 0 cur = chr(96+j) for k in range(0, 27): sum += self.skip1[chr(96+k), prev] * self.cpt.conditional_prob(cur, chr(96+k)) table[prev, cur] = sum return table
91f7b60a8fd8f7b3518b40755a12b2cdf3038e5e
llubu/AI
/Project 4/machine_learning/question3_solver.py
2,047
3.859375
4
import math class Question3_Solver: def __init__(self): return; # Add your code here. # Return the centroids of clusters. # You must use [(30, 30), (150, 30), (90, 130)] as initial centroids #[(30, 60), (150, 60), (90, 130)] def solve(self, points): centroids = [(30, 30), (150, 30), (90, 130)] #centroids = [(30, 60), (150, 60), (90, 130)] while(1): final = [[],[],[]] centroid1 = [(), (), ()] minIndex = -1 #Get distance from each current centroid for point in points: d1 = self.getDistance(centroids[0], point) d2 = self.getDistance(centroids[1], point) d3 = self.getDistance(centroids[2], point) #Find closest centroid if d1 < d2: minIndex = 0 if d3 < d1: minIndex = 2 elif d3 < d2: minIndex = 2 else: minIndex = 1 final[minIndex].append(point) #Compute new centroid for i in range(0,3): xsum = 0 ysum = 0 for item in final[i]: xsum += item[0] ysum += item[1] centroid1[i] = (xsum/len(final[i]), ysum/len(final[i])) #If centroids don't change, terminate if ( centroid1[0] == centroids[0] and centroid1[1] == centroids[1] and centroid1[2] == centroids[2]): break else: centroids = centroid1 centroid1 = [(), (), ()] return centroids; def getDistance(self, p1, p2): """ Helper function to get the distance between two points p1 and p2 """ dis = math.pow( math.pow (( p2[0] - p1[0]), 2) + math.pow (( p2[1] - p1[1]), 2), 0.5) return dis
6b72e1414ffa164e5753a0d701ca7b29098fa82c
ChengBinJin/Tensorflow-SungKim
/src/ML_lab_03.py
899
3.6875
4
import tensorflow as tf # import matplotlib.pyplot as plt x_data = [1., 2., 3.] y_data = [1., 2., 3.] W = tf.Variable(tf.random_normal([1]), name='weight') X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) # Our hypothesis for linear model X * W hypothesis = X * W # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize: Gradient Descent using derivate: W -= learning_rate * derivative learning_rate = 0.1 gradient = tf.reduce_mean((W * X - Y) * X) descent = W - learning_rate * gradient update = W.assign(descent) # Launch the graph in a session. sess = tf.Session() # Initializes global variables in the graph. sess.run(tf.global_variables_initializer()) for step in range(21): sess.run(update, feed_dict={X: x_data, Y: y_data}) print('Step: {}'.format(step), 'cost: {}, W: {}'.format(sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W)))
83a4be2a2ac283fafb84d62420c65d8d118383ab
yanolsh/dev-sprint2
/chap7.py
613
4.0625
4
# Enter your answrs for chapter 7 here # Name: # Ex. 7.5 import math def fact(k): if k == 0: return 1 else: rec = fact(k-1) result = k * rec return result def estimate_pi(): t = 0 k = 0 factor = 2 * math.sqrt(2) / 9801 while True: num = fact(4*k) * (1103 + 26390*k) den = fact(k)**4 * 396**(4*k) term = factor * num / den t += term if abs(term) < 1e-15: break k += 1 print k return 1 / t print estimate_pi() # How many iterations does it take to converge? # it takes 2 iterations.
954577d721fc5226cec27b13688bf039cc253360
aiqiliu/algoprep
/15.py
3,761
3.671875
4
# 3sum: # 1. get len # return [] if len<3 # split the list into <= 0 and > 0 # recursion, for every num1 in l1, pair up with num2 in l2. # if (0 - num1 - num2) in num1 or in num2, append the [num1, num2, 0-num1-num2] in result # first iteration: problem - have duplicates class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] l1 = [num1 for num1 in nums if num1 <= 0] l2 = [num2 for num2 in nums if num2 > 0] for num1 in l1: for num2 in l2: curr = [num1, num2] num3 = 0 - num1 - num2 if num3 in l1 or num3 in l2: curr.append(num3) result.append(curr) return result # second iteration: add a dict to indicate if num1 has occured before class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] dict = {} l1 = [num1 for num1 in nums if num1 <= 0] l2 = [num2 for num2 in nums if num2 > 0] for num1 in l1: if num1 not in dict: dict[num1] = 1 for num2 in l2: curr = [num1, num2] num3 = 0 - num1 - num2 if num3 in nums: if num3 in curr and nums.count(num3) > 1: curr.append(num3) result.append(curr) result = [sorted(l) for l in result] result = set(tuple(x) for x in result) result = [list(x) for x in result] return result # third iteration: ignored that all elements may be 0 # second iteration: add a dict to indicate if num1 has occured before class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] dict = {} if all(x == 0 for x in nums): return [[0,0,0]] l1 = [num1 for num1 in nums if num1 <= 0] l2 = [num2 for num2 in nums if num2 > 0] if l1.count(0) >= 3: result.append([0,0,0]) for num1 in l1: if num1 not in dict and num1 != 0: dict[num1] = 1 for num2 in l2: curr = [num1, num2] num3 = 0 - num1 - num2 if num3 in nums: if num3 in curr and nums.count(num3) > 1 or num3 not in curr and nums.count(num3) > 0: curr.append(num3) result.append(curr) result = [sorted(l) for l in result] result = set(tuple(x) for x in result) result = [list(x) for x in result] return result # fourth iteration # neater solution, with O(N^2) complexity class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] for i in range(0, m-2): if i > 0 and nums[i] == nums[i-1]: continue j, k = i + 1, m - 1 target = 0 - nums[i] while j < k: if j > i + 1 and nums[j] == nums[j-1]: j += 1 continue if nums[j] + nums[k] == target: result.append([nums[i], nums[j], nums[k]]) j += 1 k -= 1 elif nums[j] + nums[k] < target: j += 1 else: k -= 1 return result
c1705f2e61d5dc83e340aa1c9452e0731a669174
varinder-singh/EVA4
/S11/drawCyclicCurve.py
1,714
3.5
4
class PlotTheCurve(): def __init__(self, cycle_count, lr_min, lr_max, step_size): self.cycle_count = cycle_count self.lr_min = lr_min self.lr_max = lr_max self.step_size = step_size def setX(self,cycle,cycle_count): list1 = [] mincycleval, maxcycleval = cycle step_size = maxcycleval-mincycleval minim = mincycleval for i in range(mincycleval,(step_size * self.cycle_count)+1): if i-minim==step_size: list1.append(i) minim = i list1.append(i) return list1[:step_size*self.cycle_count] def setY(self,minval, maxval, cycle, step_size): list2 = [] for i in range(cycle): list2.append(minval) list2.append(maxval) list2.append(minval) return list2[:cycle*step_size] def plot(self): import matplotlib.pyplot as plt cycle_count=self.cycle_count # x axis values x = self.setX((1,3),cycle_count) #print("X ", x) # Set the minimum and maximum values of LR lr_min = self.lr_min lr_max = self.lr_max step_size = self.step_size # corresponding y axis values y = self.setY(lr_min,lr_max,cycle_count,step_size) #print("Y ", y) # plotting the points plt.plot(x, y, color='green') # naming the x axis plt.xlabel('Iterations (10e4)') # naming the y axis plt.ylabel('LR Range') # giving a title to my graph plt.title('Triangular schedule') # function to show the plot plt.show()
c7befa66246c186a74d3b744cefc83914b3f8dea
Binovizer/Python-Beginning
/TheBeginning/Demos/GuessTheNumber.py
322
3.875
4
from random import randint x = randint(1,100) print("Here We Go...") n = int(input("Guess the number: ")) while(True): if(x == n): print("Yippeee! You Guessed It Right.") break elif(x > n): print("Too Low") else: print("Too High") n = int(input("Guess Again: "))
41aa6417fa2caa63e1be5277d7da7c4be451715a
Binovizer/Python-Beginning
/GUIDemo/CreatingDropDownMenu.py
1,721
3.84375
4
from tkinter import * def doNothing(): print("This started Working") root = Tk() menu = Menu(root, tearoff = False) root.config(menu = menu) submenu = Menu(menu, tearoff = False) menu.add_cascade(label='File', menu = submenu) submenu.add_command(label='New Project', command = doNothing) submenu.add_command(label='New...', command=doNothing) submenu.add_separator() submenu.add_command(label='Quit', command=root.destroy) editMenu = Menu(menu, tearoff = False) menu.add_cascade(label='Edit', menu=editMenu) editMenu.add_command(label="Redo", command=doNothing) root.mainloop() # from tkinter import * # # def doNothing(): # print("Ok, ok I won't!") # # root = Tk() # # menu = Menu(root, tearoff = False) # Creates menu object # root.config(menu = menu) # Configuring menu object to be a menu # # subMenu = Menu(menu, tearoff = False) # Creating a menu inside a menu # # menu.add_cascade(label = "File", # menu = subMenu) # Creates file button with dropdown, sub menu is the drop # # subMenu.add_command(label = "New project", # command = doNothing) # subMenu.add_command(label = "New...", # command = doNothing) # 2 commands in the sub menu now # # subMenu.add_separator() # Creates seperator in the drop # # subMenu.add_command(label = "Exit", # command = root.destroy) # Another sub menu item # # editMenu = Menu(menu, tearoff = False) # Create another item in main menu # # menu.add_cascade(label = "Edit", # menu = editMenu) # # editMenu.add_command(label = "Redo", # command = doNothing) # # root.mainloop()
eb78d593489b33d1a5cd3cb14268aef27b553962
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/50.py
897
4.1875
4
import re student_id = input("Enter student id : ") if(re.search("[^0-9]", student_id)): print("Sorry! Student ID can only contains digit") else: student_name = input("Enter student name : ") if re.search("[^a-zA-Z]", student_name): print("Name can only contain alphabets") else: print("Hello",student_name.capitalize()) fees_amount = input("Enter Fees Amount : ") if re.search("^\d+(\.\d{1,2})?$", fees_amount): college_name = "akgec" email_id = student_name.lower()+"@"+college_name+".com" print("\nStudent ID : ",student_id) print("Student Name : ",student_name) print("Student Fees : ",fees_amount) print("Student Email ID : ",email_id) else: print("Sorry! Only two digits are allowed after decimal point")
67372b5d84a298c77462a0979c9e52eafaffe948
Binovizer/Python-Beginning
/TheBeginning/Demos/DateNTimeDemo.py
327
3.546875
4
import time import datetime print(time.clock()) print(time.gmtime()) print(time.localtime()) print(time.time()) print(time.daylight) print(datetime.datetime.now()) print(datetime.datetime.now()+datetime.timedelta()) print("Current Time : "+time.strftime("%c")) print(time.strftime("%x")) print(time.strftime("%X"))
a54f5599368ec0d5a7a425a7cba6efa0795e67ff
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/32.py
359
3.875
4
a = [int(x) for(x) in input("Enter numbers : ").split(sep=' ')] #Taking list as an input print("List before sorting : ",a) #Bubble Sort for i in range(0,len(a)) : for j in range(0,len(a)-i-1) : if (a[j] < a[j+1]): temp = a[j]; a[j] = a[j+1]; a[j+1] = temp print("List after sorting : ",a)
e9a65f7f1552fb9dc8b79e7f6d8147b7f148874d
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/17.py
101
3.84375
4
counter = 1 while (counter <= 3): print(counter) counter += 1 print("End of program")
2edf97fc3e08b52cbe3646a770eacc4800fec38d
Binovizer/Python-Beginning
/GUIDemo/FittingWidgets.py
288
3.9375
4
from tkinter import * root = Tk() one = Label(root, text='One', fg='black', bg="red") two = Label(root, text='Two', fg='red', bg='yellow') three = Label(root, text='Three', fg='red', bg='blue') one.pack() two.pack(fill=X) three.pack(fill=BOTH, expand=TRUE) root.mainloop()
f1ec84bd827159d3638ce26957379c9a20d5ed2b
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/33.py
708
4.09375
4
furniture_list = [("SofaSet",20000),("Dining Table",8500),("TV stand",4599),("Cupboard",13920)] fur_name = input("Enter the Name of furniture You want to buy : ").strip() for fur_tuple in furniture_list: if (fur_tuple[0].lower() == fur_name.lower()): price = fur_tuple[1] print("\nFurniture Name : ",fur_tuple[0],", Price : ",price) no = int(input("\nEnter Quantity : ").strip()) bill_amount = price * no; print("\nFurniture Name : ",fur_tuple[0],", Price : ",price) print("Quantity : ",no) print("Bill Amount : ",bill_amount) print("Thank You for Shopping With Us ;)") break; else: print("No Results Found")
1055bc0e42e910b94362ab9eca8562dd189a4ad7
bocchini/py_todo
/view/add_to_do.py
522
3.6875
4
from controllers.to_do_controller import add_to_do def add(): print('*' * 30, '-' * 4, ' Adicionar uma tarefa ', '-' * 4, '*' * 30) save = False while not save: title = input('Digite o titulo da tarefa: ').capitalize() to_do = input('Digite a tarefa: ').capitalize() want_to_save = input('Salvar a tarefa? (s/n) ') if want_to_save.lower() == 's': save = True do = add_to_do(title, to_do) print('Tarefa adicionada') print(do)
ae49e7d82f3936422004eea0e1f73d0f58feb126
messophet/Google
/Algorithms/CTCI/Chapter 1 - Arrays and Strings/35.py
432
3.90625
4
class Stack: def __init__(self): self.items=[] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def size(self): return len(self.items) def isEmpty(self): return self.items==[] class MyQueue: def __init__(self): self.queue = [] #3 2 1 -stack-> 3 2 1 (LIFO) -stack-> 1 2 3 | push 4 onto s1 -> 4, s2 = 1 2 3 | s1 = 4 3 2 1... now pop and it's in FIFO #3 2 1 -queue-> 1 2 3 (FIFO)
fae008a799fc1d985d61d7801a196a802ad4f49b
messophet/Google
/Algorithms/CTCI/Chapter 1 - Arrays and Strings/graphs.py
816
3.890625
4
graph = {'A':['B','D'],'B':['C'],'C':['E','F'],'D':[],'E':[],'F':[]} def find_path(graph,start,end,path=[]): path = path + [start] if(start==end): return path if(not graph.has_key(start)): return None #shortestPath = None for node in graph[start]: if node not in path: newpath = find_path(graph,node,end,path) if newpath: return newpath return None print(find_path(graph,'A','F')) def find_shortest_path(graph,start,end,path=[]): path=path+[start] if(start==end): return path if(not graph.has_key(start)): return None shortestPath = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph,node,end,path) if newpath: if(not shortest or len(newpath) < len(path)): shortestPath = newpath return shortestPath print(find_path(graph,'A','F'))
e21fb99cb9d35f6ee1b5d7bc0b846d7479ed5b20
jiafulow/emtf-nnet
/emtf_nnet/architecture/endless_utils.py
1,615
4.03125
4
"""Architecture utils.""" import numpy as np def gather_indices_by_values(arr, max_value=None): """Gather indices by values. Instead of gathering values by indices, this function gathers indices by (non-negative integer) values in an array. The result is a nested list, which can be addressed by content from the original array. Negative values in the array are ignored. Example: >>> arr = [0, 1, 1, 2, 2, 2, 4] >>> gather_indices_by_values(arr) [[0], [1, 2], [3, 4, 5], [], [6]] """ arr = np.asarray(arr) if not (arr.dtype in (np.int64, np.int32) and arr.ndim == 1): raise TypeError('arr must be a 1-D int32 or int64 numpy array') if max_value is None: max_value = np.max(arr) return [ [i for (i, x_i) in enumerate(arr) if x_i == y_j] for y_j in range(max_value + 1) ] def gather_inputs_by_outputs(arr, default_value=-99, padding_value=-99): """Gather inputs by outputs. Assume a 2-D array that is used to map multiple inputs to a smaller number of outputs. If two or more inputs are mapped to the same output, the one with the highest priority is used as the output. """ arr = np.asarray(arr) if not (arr.dtype in (np.int64, np.int32) and arr.ndim == 2): raise TypeError('arr must be a 2-D int32 or int64 numpy array') max_value = np.max(arr) matrix_shape = (max_value + 1, len(arr)) matrix = np.full(matrix_shape, default_value, dtype=np.int32) for i, x_i in enumerate(arr): for j, x_j in enumerate(x_i): if x_j != padding_value: priority = len(x_i) - 1 - j matrix[x_j, i] = priority return matrix
1c68f6f4f392e6e800af406002a42e343b8811f0
alixoallen/todos.py
/import random.py
367
3.90625
4
import random nome=(input('digite um nome :')) nome2=(input('digite um segundo nome :')) nome3=(input('digite um terceiro nome:')) nome4=(input('digite um quarto nome :')) lista=[nome,nome2,nome3,nome4] nme=random.choice(lista) print("o nome sorteado foi {}".format(nme)) #quase fiz sozinho, nao havia colocado a lista pois nao passava na minha cabeça, dor dor dor
b09f322540e7bbeaec6e9e07238e09374110fbc8
alixoallen/todos.py
/dobro triplo e raiz.py
162
4.03125
4
n=int(input('digite um numero :')) dobro= n*2 triplo= n*3 raiz= n**(1/2) print('o dobro de {} é {}, o triplo é {} , e a raiz é {}'.format(n,dobro,triplo,raiz))
0af2fe8c20ab0c3cd1b7c9282387577f64babe72
alixoallen/todos.py
/conversor de metros, centimetros e milimetros.py
196
3.8125
4
medida=float(input('quantos metros quer converter ?')) cm= medida*100 mm=medida*1000 print('segundo a metragem que escolheu, os centimetros correspondem a {}, e os milimetros a {}'.format(cm,mm ))
50807cca27c1d9b15e8a43d36a3fe2249529c96c
alixoallen/todos.py
/adivinhação.py
327
4.15625
4
from random import randint computer=randint(0,5) print('pensei no numero{}'.format(computer))#gera um numero aleatorio, ou faz o computador """"""pensar""""""""""""""" escolha=int(input('digite um numero:')) if escolha == computer: print('parabens voce acertou!') else: print('ora ora voce é meio pessimo nisso!')
23ffb890a15d4de9ec5686c12cc2476f78c4810c
yupei0318cs/ScrapyWebCrawler
/douban_book/douban_book/utils/threadsafe_queue.py
888
3.640625
4
import queue import threading q = queue.Queue() for i in range(5): q.put(i) while not q.empty(): print (q.get()) q = queue.LifoQueue() for i in range(5): q.put(i) while not q.empty(): print (q.get()) class Task: def __init__(self, priority, description): self.priority = priority self.description = description def __lt__(self, other): return self.priority < other.priority q = queue.PriorityQueue() q.put(Task(1, 'Important Task\n')) q.put(Task(10, 'Normal Task\n')) q.put(Task(100, 'Lazy Task\n')) def job(q): while True: task = q.get() print ('Task: ', task.description) q.task_done() threads = [threading.Thread(target= job, args= (q,)), threading.Thread(target=job, args=(q,))] for t in threads: t.setDaemon(True) t.start() q.join()
ce951ed88517fc810a94b560b2c96e86395874f7
lalluz/movie_trailer_website
/media.py
1,239
3.8125
4
import webbrowser class Movie: """ This class provides a way to store movie related information. Attributes: title (str): the movie title storyline (str): a short description of the movie box_art_url (str): a url to a poster image trailer_url (str): a url to a youtube trailer video production_company (str): the production company name director (str): the director full name duration (str): the duration in minutes box_office (str): the amount of money raised by ticket sales in dollars year (str): the release year """ def __init__(self, title, storyline, box_art_url, trailer_url, production_company, director, duration, box_office, year): """ Init Movie class """ self.title = title self.storyline = storyline self.box_art_url = box_art_url self.trailer_url = trailer_url self.production_company = production_company self.director = director self.duration = duration self.box_office = box_office self.year = year def show_trailer(self): """ Open the browser at the youtube trailer url. """ webbrowser.open(self.trailer_url)
d1e7bdef1bfbdee75db0888035cbee70ddf5875c
nedraki/gym_explorer
/deep_q_network.py
1,979
3.53125
4
import tensorflow as tf from tensorflow import keras from keras.models import Model, Sequential, load_model from keras.layers import Input, Dense, Dropout from keras.optimizers import Adam, RMSprop # Neural Network model for Deep Q Learning """Deep Q-Learning As an agent takes actions and moves through an environment, it learns to map the observed state of the environment to an action. An agent will choose an action in a given state based on a "Q-value", which is a weighted reward based on the expected highest long-term reward. A Q-Learning Agent learns to perform its task such that the recommended action maximizes the potential future rewards. This method is considered an "Off-Policy" method, meaning its Q values are updated assuming that the best action was chosen, even if the best action was not chosen.""" def create_q_model(input_shape: int, num_actions: int): """A model of Dense layers (fully connected layers) to train an agent using reinforcement learning. input_shape: Comes from observation of the environment. `env.observation_space.shape[0]` num_actions: Number of available actions that can be taken by the agent. `env.action_space.n` For more specific NN, you can find research of Deep Mind research at: [docs](https://keras.io/examples/rl/deep_q_network_breakout/) """ model = Sequential() model.add(Dense(512, activation='relu', input_shape=(input_shape,))) #model.add(Dropout(0.1)) model.add(Dense(256, activation='relu')) model.add(Dense(64, activation='relu')) #model.add(Dropout(0.1)) model.add(Dense(num_actions, activation='softmax')) # model = Model(inputs=X_input, outputs=model, name='trained_model') # In the Deepmind paper they use RMSProp however then Adam optimizer # improves training time model.compile(loss="mse", optimizer=Adam( learning_rate=0.001, epsilon=1e-07), metrics=["accuracy"]) model.summary() return model
39f15cc411cd352495194da5849953befe4edb07
Recky-krec/Python-BS4
/youtube-searcher-master/youtube-searcher.py
1,365
3.578125
4
#!/usr/bin/python3 import bs4 as bs import urllib.request import re import os def webRequest(url): """Creates a request based in the url""" headers = {"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"} req = urllib.request.Request(url, headers=headers) #Creating a request raw_sauce = urllib.request.urlopen(req) #Opening url with created request sauce = raw_sauce.read() #Source code soup = bs.BeautifulSoup(sauce, features="lxml") #Creating BS4 object return soup def youtubeSearch(): """Use user input for retrieving desired background""" query = input("Insert query: ") #this is a trivial input method, consider changing it ;) query_keywords = query.split(" ") print("+".join(query_keywords)) url = 'https://www.youtube.com/results?search_query=' + "+".join(query_keywords) return url def writeToFile(url_list): with open("found_urls.txt", "w") as f: for url in url_list: f.write("www.youtube.com{url}\n".format(url=url)) def parse(): url_list = [] url = youtubeSearch() source = webRequest(url) pattern = r'/watch' for link in source.find_all('a'): link = link.get('href') if re.match(pattern, link): url_list.append(link) return url_list if __name__ == "__main__": url_list = parse() writeToFile(url_list)
ac1615321ed322852494f2d9e039a2756c8b6a55
mansiagnihotrii/Data-Structures-in-python
/Strings/5_single_edit.py
852
3.8125
4
''' Check whether the strings entered are one or zero edit away. Edits performed are: insert a character, remove a character, or replace a character ''' def single_edit(s1, s2): if s1 == s2: return True if abs(len(s1) - len(s2)) > 1: return False short_str = s1 if len(s1) < len(s2) else s2 long_str = s1 if len(s1) > len(s2) else s2 len_short_str = len(short_str) len_long_str = len(long_str) index1, index2 = 0, 0 found = False while index2< len_long_str and index1 < len_short_str: if short_str[index1] != long_str[index2]: if found: return False found =True if len_short_str == len_long_str: index1 += 1 else: index1 += 1 index2 += 1 return True s1 = input("Enter first string: ") s2 = input("Enter second string: ") print(single_edit(s1, s2))
9eb137a3f310eeb8c6d006bfd72fce5e035e06b2
mansiagnihotrii/Data-Structures-in-python
/Linked List/4_linkedlist_partition.py
851
4.125
4
''' Given a linked list and an element , say 'x'. Divide the same list so that the left part of the list has all the elements less that 'x' and right part has all elements greater than or equal to 'x'. ''' #!/usr/bin/env python3 import linkedlist from linkedlist import LinkedList,Node def partition_list(head,element): start = head new = LinkedList() new.head = Node(start.data) start = start.next while start: if start.data >= element: linkedlist.insert_end(new.head,start.data) else: new.head = linkedlist.insert_beg(new.head,start.data) start = start.next return new.head list1 = LinkedList() head = linkedlist.create_list(list1) element = input("Enter partition element: ") if head is None: print("List is empty") else: new_head = partition_list(head,element) linkedlist.printlist(new_head)
af7a3b336d50ddea1a8c4ec76a767f3143fdc44f
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/greedy/largest_permutation.py
2,068
4.09375
4
def largest_permutation(k, arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/largest-permutation/problem You are given an unordered array of unique integers incrementing from 1. You can swap any two elements a limited number of times. Determine the largest lexicographical value array that can be created by executing no more than the limited number of swaps. For example, if arr = [1, 2, 3, 4] and the maximum swaps k = 1, the following arrays can be formed by swapping the 1 with the other elements: [2,1,3,4] [3,2,1,4] [4,2,3,1] The highest value of the four (including the original) is [4, 2, 3, 1]. If k >= 2, we can swap to the highest possible value: [4, 3, 2, 1]. Solve: We store the values in a dictionary so we can access the position of each value in O(1) speed. We then iterate through the list starting at the highest value, and swap it IF it isn't already in the correct position. We then update the dictionary with the swapped values, and then proceed to the next value to swap. Args: k (int): Number of swaps to perform arr (list): List of numbers where 1 <= arr[i] <= n Returns: list containing the largest lexicographical value array after k swaps """ sorted_array = sorted(arr, reverse=True) vals = {v: idx for idx, v in enumerate(arr)} c = 0 m = len(arr) while k > 0 and c < len(arr): if arr[c] != sorted_array[c]: # Swap the current highest value swap = arr[c] arr[c] = m arr[vals[m]] = swap # Update dictionary prev = vals[m] vals[m] = c vals[swap] = prev k -= 1 m -= 1 c += 1 return arr if __name__ == "__main__": print(largest_permutation(1, [4, 2, 3, 5, 1])) print(largest_permutation(2, [4, 2, 3, 5, 1])) print(largest_permutation(2, [4, 3, 2, 5, 1])) print(largest_permutation(1, [2, 1, 3])) print(largest_permutation(1, [2, 1]))
c696a2980ffe52412000a0f0deda444cea00badf
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/funny_string.py
1,059
4.34375
4
def funny_string(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/funny-string/problem In this challenge, you will determine whether a string is funny or not. To determine whether a string is funny, create a copy of the string in reverse e.g. abc -> cba. Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny. Determine whether a give string is funny. If it is, return Funny, otherwise return Not Funny. Args: s (str): String to check Returns: str: Returns "Funny" or "Not Funny" based on the results of the string """ for i in range(len(s)//2): if abs(ord(s[i]) - ord(s[i+1])) != abs(ord(s[len(s)-i-1]) - ord(s[len(s)-i-2])): return "Not Funny" return "Funny" if __name__ == "__main__": assert funny_string("acxz") == "Funny" assert funny_string("bcxz") == "Not Funny"
131e45b4fcdb5a3ef8a9efa3580a1ac03bda66f6
kcc3/hackerrank-solutions
/python/numpy/min_and_max.py
432
3.9375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/np-min-and-max/problem Task You are given a 2-D array with dimensions N x M. Your task is to perform the min function over axis 1 and then find the max of that. """ import numpy n, m = map(int, input().split(' ')) array = [] for _ in range(n): a = list(map(int, input().split(' '))) array.append(a) min_array = numpy.min(array, axis=1) print(max(min_array))
0562ecb6074ee2c8d62d863db65a1c5a5325fd66
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/mars_exploration.py
919
4.34375
4
def mars_exploration(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/mars-exploration/problem Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help. Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string, s, determine how many letters of Sami's SOS have been changed by radiation. For example, Earth receives SOSTOT. Sami's original message was SOSSOS. Two of the message characters were changed in transit. Args: s (str): string to compare with SOS message (must be divisible by 3) Returns: int: the number of characters that differ between the message and "SOS" """ sos = int(len(s)/3) * "SOS" return sum(sos[i] != s[i] for i in range(len(s))) if __name__ == "__main__": assert mars_exploration("SOSSPSSQSSOR") == 3
ff2f6d4c31e79e2249438839b9e85049e4f2c4e0
kcc3/hackerrank-solutions
/python/python_functionals/validating_email_addresses_with_filter.py
1,146
4.15625
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain letters, digits, dashes and underscores [a-z], [A-Z], [0-9], [_-]. The website name can only have letters and digits [a-z][A-Z][0-9] The extension can only contain letters [a-z][A-Z]. The maximum length of the extension is 3. Args: s (str): Email address to check Returns: (bool): Whether email is valid or not """ if s.count("@") == 1: if s.count(".") == 1: user, domain = s.split("@") website, extension = domain.split(".") if user.replace("-", "").replace("_", "").isalnum(): if website.isalnum(): if extension.isalnum(): if len(extension) <= 3: return True return False if __name__ == "__main__": test = "itsallcrap" print(fun(test))
10a395af6ac6efa71d38074c2d88adff4665435e
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/bit_manipulation/maximizing_xor.py
932
4.3125
4
def maximizing_xor(l, r): """Hackerrank Problem: https://www.hackerrank.com/challenges/maximizing-xor/problem Given two integers, l and r, find the maximal value of a xor b, written a @ b, where a and b satisfy the following condition: l <= a <= b <= r Solve: We XOR the l and r bound and find the length of that integer in binary form. That gives us the binary from which we can create the highest value of a xor b, because that falls within l and r. Args: l (int): an integer, the lower bound inclusive r (int): an integer, the upper bound inclusive Returns: int: maximum value of the xor operations for all permutations of the integers from l to r inclusive """ xor = l ^ r xor_binary = "{0:b}".format(xor) return pow(2, len(xor_binary)) - 1 if __name__ == "__main__": print(maximizing_xor(10, 15)) print(maximizing_xor(11, 100))
5dada4e2c555cf79880499431e25a16d8a441ad3
kcc3/hackerrank-solutions
/python/numpy/zeros_and_ones.py
617
3.96875
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/np-zeros-and-ones/problem Task You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones. """ import numpy # Read in the number of lines to parse dimensions = list(map(int, input().split(' '))) # Convert array to a bumpy array and print out transpose and flatten print(numpy.zeros(dimensions, dtype=numpy.int32)) print(numpy.ones(dimensions, dtype=numpy.int32))
6d15fcd0279049189d9a54c882f0b27a46034a59
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/the_grid_search.py
2,824
4.21875
4
def grid_search(g, p): """Hackerrank Problem: https://www.hackerrank.com/challenges/the-grid-search/problem Given a 2D array of digits or grid, try to find the occurrence of a given 2D pattern of digits. For example: Grid ---------- 1234567890 0987654321 1111111111 1111111111 2222222222 Pattern ------ 876543 111111 111111 The 2D pattern begins at the second row and the third column of the grid. The pattern is said to be present in the grid. Args: g (list): The grid to search, an array of strings p (list): The pattern to search for, an array of strings Returns: str: "YES" or "NO" depending on whether the pattern is found or not """ for i in range(len(g)-len(p)+1): # If we find a match for the first line, store the indices to search for match = [x for x in range(len(g[i])) if g[i].startswith(p[0], x)] if match: # Iterate through the list of indices where the first line of the pattern matched for j in match: found = True # Now see if the rest of the pattern matches within the same column / index for k in range(1, len(p)): if p[k] == g[i+k][j:j+len(p[k])]: continue else: found = False break if found: return "YES" return "NO" if __name__ == "__main__": g = ["7283455864", "6731158619", "8988242643", "3830589324", "2229505813", "5633845374", "6473530293", "7053106601", "0834282956", "4607924137"] p = ["9505", "3845", "3530"] assert grid_search(g, p) == "YES" g2 = ["7652157548860692421022503", "9283597467877865303553675", "4160389485250089289309493", "2583470721457150497569300", "3220130778636571709490905", "3588873017660047694725749", "9288991387848870159567061", "4840101673383478700737237", "8430916536880190158229898", "8986106490042260460547150", "2591460395957631878779378", "1816190871689680423501920", "0704047294563387014281341", "8544774664056811258209321", "9609294756392563447060526", "0170173859593369054590795", "6088985673796975810221577", "7738800757919472437622349", "5474120045253009653348388", "3930491401877849249410013", "1486477041403746396925337", "2955579022827592919878713", "2625547961868100985291514", "3673299809851325174555652", "4533398973801647859680907"] p2 = ["5250", "1457", "8636", "7660", "7848"] assert grid_search(g2, p2) == "YES" g3 = ["111111111111111", "111111111111111", "111111011111111", "111111111111111", "111111111111111"] p3 = ["11111", "11111", "11110"] assert grid_search(g3, p3) == "YES"
24ea0ea11b64dd814811282faa67c89274005133
kcc3/hackerrank-solutions
/python/numpy/transpose_and_flatten.py
735
4.0625
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem Task You are given a X integer array matrix with space separated elements ( = rows and = columns). Your task is to print the transpose and flatten results. """ import numpy # Initialize array array = [] # Read in the number of lines to parse n, m = input().split(' ') # Iterate through each line and add to the array array = [] for _ in range(int(n)): line = input() array_map = map(int, line.split(' ')) cur_array = numpy.array(list(array_map)) array.append(cur_array) # Convert array to a bumpy array and print out transpose and flatten array = numpy.array(array) print(numpy.transpose(array)) print(array.flatten())
6eba8809d2c6d10aadc221ea78cf0d08d458d967
kcc3/hackerrank-solutions
/data_structures/python/stacks/maximum_element.py
1,176
4.34375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/maximum-element/problem You have an empty sequence, and you will be given queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. """ # Enter your code here. Read input from STDIN. Print output to STDOUT # Setup the list which will act as our stack stack = [-1] # Read in the total number of commands num_commands = int(input()) # For each command, append, pop, or return the max value as specified. When we push to the stack, we can compare # with the current highest value so that the stack always has the max value at the tail of the list, and because when # we pop, we are removing the last added item, so it is either the last added value, or a copy of the last max value # when it was added for _ in range(num_commands): query = input().split(" ") if query[0] == "1": stack.append(max(int(query[1]), stack[-1])) elif query[0] == "2": stack.pop() elif query[0] == "3": print(stack[-1]) else: print("Unknown command")
54e29a17af6dfcb36c102bba527a588a533d29f3
kcc3/hackerrank-solutions
/python/built_ins/any_or_all.py
548
4.15625
4
""" Hackerrank Problem: https://www.hackerrank.com/challenges/any-or-all/problem Given a space separated list of integers, check to see if all the integers are positive, and if so, check if any integer is a palindromic integer. """ n = int(input()) ints = list(input().split(" ")) # Check to see if all integers in the list are positive if all(int(i) >= 0 for i in ints): # Check if any of the integers are a palindrome - where the digit number is the same if digits are reversed print(any(j == j[-1] for j in ints)) else: print(False)
3cc86ea1557ecd260202121ce31df104a83d1b09
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/taum_and_bday.py
1,606
4.09375
4
def taum_bday(b, w, bc, wc, z): """Hackerrank Problem: https://www.hackerrank.com/challenges/taum-and-bday/problem Taum is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy b black gifts and w white gifts. - The cost of each black gift is bc units. - The cost of every white gift is wc units. - The cost of converting each black gift into white gift or vice versa is z units. Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts. For example, if Taum wants to buy b = 3 black gifts and w = 5 white gifts at a cost of bc = 3, wc = 4 and conversion cost z = 1, we see that he can buy a black gift for 3 and convert it to a white gift for 1, making the total cost of each white gift 4. That matches the cost of a white gift, so he can do that or just buy black gifts and white gifts. Either way, the overall cost is 3 * 3 + 5 * 4 = 29. Args: b (int): The number of black presents to purchase w: (int): The number of white presents to purchase bc (int): The cost of each black present wc (int): The cost of each white present z (int): The cost to switch between the present types Returns: int: the optimized cost to buy the specified presents """ return b * min(bc, wc + z) + w * min(wc, bc + z) if __name__ == "__main__": print taum_bday(3, 5, 3, 4, 1) print taum_bday(10, 10, 1, 1 , 1) print taum_bday(5, 9, 2, 3, 4)
048f4a1843a7cb34f846a62ff3cc70225a74c763
kcc3/hackerrank-solutions
/data_structures/python/stacks/balanced_brackets.py
2,594
4.40625
4
def is_balanced(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/balanced-brackets/problem A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]. By this logic, we say a sequence of brackets is balanced if the following conditions are met: - It contains no unmatched brackets. - The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO. Args: s (str): The string to compare Returns: (str): "YES" or "NO" based on whether the brackets in the string are balanced """ open_closed = {"(": ")", "[": "]", "{": "}"} balanced = [] for i in s: if i in open_closed.keys(): balanced.append(i) else: # If the stack is empty, we have a closed bracket without any corresponding open bracket so not balanced if len(balanced) == 0: return "NO" # Compare the brackets to see if they correspond, and if not, not balanced if i != open_closed[balanced.pop()]: return "NO" # If the stack is empty, every open bracket has been closed with a corresponding closed bracket if not balanced: return "YES" # If there's still something in the stack, then return NO because it's not balanced return "NO" if __name__ == "__main__": assert is_balanced("}}}") == "NO" assert is_balanced("{[()]}") == "YES" assert is_balanced("{[(])}") == "NO" assert is_balanced("{{[[(())]]}}") == "YES" assert is_balanced("{{([])}}") == "YES" assert is_balanced("{{)[](}}") == "NO" assert is_balanced("{(([])[])[]}") == "YES" assert is_balanced("{(([])[])[]]}") == "NO" assert is_balanced("{(([])[])[]}[]") == "YES"