blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4fb087fd599813b8a13554b1530a04edd96a8103
freddieaviator/my_python_excercises
/ex042/ex02.py
303
3.890625
4
first_name = "fredrik" last_name = "hårberg" course = "Data Engineer" candidates = 11 print(f"""My name is {first_name.capitalize()} with last name {last_name.capitalize()}. I am participating in the course {course.lower()}. There are {candidates} candidates taking the {course.lower()} course.""")
dff2db36e5f3cf6b30bd9266221f77f039469301
CharlesJonah/andela_ex_d1
/fizz_buzz.py
365
4.1875
4
def fizz_buzz(num): #Return FizzBuzz if num is divisible by both 3 and 5 if num % 3 == 0 and num % 5 == 0: return 'FizzBuzz' #Returns Buzz if num is divisible by 5 elif num % 5 == 0: return 'Buzz' #Returns Fizz if num is divisible by 3 elif num % 3 == 0: return 'Fizz' #Returns num itself if it is not divisible by either 3 or 5 else: return num
55221d27a289720d001a5e6b612cb6534e8e470a
shubham-dixit-au7/test
/coding-challenges/Week03/Day01_(03-02-2020)/Ques3.py
585
4.28125
4
# Question- Write a Python program to create a dictionary from a string. # Note: Track the count of the letters from the string. # Sample string : 'w3resource' # Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1} # Answer- # first method- # user_input = input("Enter a String ->") # counts= {} # for i in user_input: # if not i in counts: # counts[i] = 1 # else: # counts[i] += 1 # print(counts) # Second method- user_input = input("Enter a String -> ") counts= {} for i in user_input: counts[i]=counts.get(i,0) + 1 print(counts)
449cc995d85aceb7296751501136209c535dec42
maksim-shaidulin/CodeSignalTasks
/LeetCode/plusOne.py
446
3.53125
4
from typing import List class Solution: def plusOne(self, digits: List[int]) -> List[int]: num = int("".join([str(x) for x in digits])) + 1 return [int(x) for x in str(num)] def test_plusOne(): assert Solution().plusOne([0]) == [1] assert Solution().plusOne([1]) == [2] assert Solution().plusOne([9]) == [1, 0] assert Solution().plusOne([1, 2]) == [1, 3] assert Solution().plusOne([9, 9]) == [1, 0, 0]
43dd7834732752e8c4215516f9fab5c775e5afb4
Iliaromanov/classroom-examples_gr11
/arcade/11_lists_motion_01.py
1,234
4
4
""" 1. Create parallel lists of rain x and y values. 2. In the draw function, use a for loop with zip() to draw rain at the x, y co-ordinates. """ import arcade WIDTH = 640 HEIGHT = 480 # Parallel lists to store x and y values for each rain drop rain_x_positions = [100, 200, 300] rain_y_positions = [480, 480, 480] def setup(): arcade.open_window(WIDTH, HEIGHT, "My Arcade Game") arcade.set_background_color(arcade.color.WHITE) arcade.schedule(update, 1/60) # Override arcade window methods window = arcade.get_window() window.on_draw = on_draw window.on_key_press = on_key_press window.on_key_release = on_key_release window.on_mouse_press = on_mouse_press arcade.run() def update(delta_time): pass def on_draw(): arcade.start_render() # Draw in here... # zip() pairs up values from multiple lists for we can # iterate through multiple lists at once for x, y in zip(rain_x_positions, rain_y_positions): arcade.draw_circle_filled(x, y, 25, arcade.color.BLUE) def on_key_press(key, modifiers): pass def on_key_release(key, modifiers): pass def on_mouse_press(x, y, button, modifiers): pass if __name__ == '__main__': setup()
01406dca128ecd3caf10f7f3c59b81ec94a1bb27
tektutor/DevOpsJuly2018
/Day6/Python/inheritance.py
965
4.0625
4
#!/usr/bin/python class Parent: def __init__(self): print ( 'Parent constructor' ) self.x = 0 self.y = 0 def setValues(self, a, b): self.x = a self.y = b def printValues(self): print ('The value of x is' , self.x ) print ('The value of y is' , self.y ) def __privateMethod(self): print ('Parent private method') class Child(Parent): def __init__(self): Parent.__init__(self) print ( 'Child constructor') self.z = 0 def setValues(self, a, b, c ): Parent.setValues (self, a, b) self.z = c def printValues(self): Parent.printValues(self) print ('The value of z is', self.z ) def main(): child = Child() child.printValues() child.setValues ( 100, 200, 300 ) child.printValues() #child.__privateMethod() #if uncommented gives an error as private methods aren't inherited by child main()
38c4f4d57a469bc6575bc82c77ef83eae3529b48
tuftsceeo/EDL2020
/student_notebook_root_folder/archive/image_processing/python_scripts/apply_face_detection.py
2,309
3.640625
4
import cv2 import argparse def detect_face(img, faceCascade, eyeCascade): """ Name: detect_face Input: image(numpy 3d array), face classifier, eye classifier Return: n/a What it does: draws red box around face, draws green box around eye """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags= cv2.CASCADE_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2) # roi stands for region of interest-- eyes always on the face roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eyeCascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) def face_detect_video(inputVideoPath, outputVideoPath): """ Name: face_detect_video Input: path to video, path to output Return: none What it does: detects faces and eyes for an entire video """ # read existing video in folder cap = cv2.VideoCapture(inputVideoPath) # use face detection classifier in folder # it's good practice to have paths be variables so they are easily edited cascPath = '../haarcascades/lbpcascade_frontalface_improved.xml' eyeCascPath = '../haarcascades/haarcascade_eye.xml' faceCascade = cv2.CascadeClassifier(cascPath) eyeCascade = cv2.CascadeClassifier(eyeCascPath) # output file fourcc = 0x00000021 out = cv2.VideoWriter(outputVideoPath, fourcc, 20.0, (640,480)) i = 0 while(cap.isOpened()): if i %40 ==0: print(i) i +=1 ret, frame = cap.read() if ret is False: break detect_face(frame, faceCascade, eyeCascade) out.write(frame) cap.release() cv2.destroyAllWindows() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("inputPath", help = "path to video") parser.add_argument("outputPath", help = "path to output as mp4") args = parser.parse_args() face_detect_video(args.inputPath, args.outputPath)
006fb1c33f5bf0649de9c7da3a761f3a892e3d0f
dark-polar/tech-test
/programmer.py
483
3.890625
4
words = ["pro", "gram", "merit", "program", "it", "programmer"] patterns = "program" matching = [s for s in words if patterns in s] def check(n): array = ['pro', 'gram', 'merit', 'program', 'it', 'programmer'] result = '' cut = False for i in array: if i in n: result += '{}, '.format(i) else: cut = True if cut: pass else: print(result) check('programmerit') print(matching)
be2970af9bcb6736ce21f3009bbc1108cbe8d0da
gcrowder/currency_converter
/currency_test.py
2,051
3.578125
4
import unittest import currency first_currency_object = currency.Currency('£5.25') second_currency_object = currency.Currency(currency_code='GBP', amount=5.25) third_currency_object = currency.Currency(amount=5.25, currency_code='EUR') fourth_currency_object = currency.Currency('£10.50') class TestCurrency(unittest.TestCase): def test_assert_equal(self): self.assertEqual(first_currency_object, second_currency_object) def test_assert_not_equal_currency_code(self): self.assertNotEqual(second_currency_object, third_currency_object) def test_assert_not_equal_amount(self): self.assertNotEqual(first_currency_object, fourth_currency_object) def test_assert_equal_add(self): self.assertEqual(first_currency_object + second_currency_object, fourth_currency_object) def test_assert_not_equal_add(self): self.assertNotEqual(first_currency_object + currency.Currency('£8.75'), fourth_currency_object) def test_assert_raises_add(self): self.assertRaises(currency.DifferentCurrencyCodeError, lambda: first_currency_object + third_currency_object) def test_assert_equal_sub(self): self.assertEqual(fourth_currency_object - first_currency_object, second_currency_object) def test_assert_not_equal_sub(self): self.assertNotEqual(second_currency_object - first_currency_object, fourth_currency_object) def test_assert_raises_sub(self): self.assertRaises(currency.DifferentCurrencyCodeError, lambda: fourth_currency_object - third_currency_object) def test_assert_equal_mul(self): self.assertEqual(first_currency_object * second_currency_object, currency.Currency('£27.56')) def test_assert_not_equal_mul(self): self.assertNotEqual(first_currency_object * second_currency_object, currency.Currency('£900')) def test_assert_raises_mul(self): self.assertRaises(currency.DifferentCurrencyCodeError, lambda: first_currency_object * third_currency_object) if __name__ == '__main__': unittest.main()
9382a54fbddb47a1500e6b4e3f1729b72a24a9f3
KenOasis/LeetCode
/LeetCode/Algorithm/Longest Palindromic Substring/main.py
1,748
3.671875
4
class Solution: def palindrome(self , start , end , s ): while True: if(start < 0 or end > len(s) - 1 ): break if(s[start] != s[end]): break start -= 1 end += 1 return end - start - 1 def longestPalindrome(self, s: str) -> str: if(len(s) == 1): return s start = 0 end = 0 #from the middle for i in range(0,len(s)) : l = self.palindrome(i , i , s) l1 = self.palindrome(i , i + 1 , s ) l2 = max(l , l1) if(l2 > end - start + 1 ): start = i - (l2-1)//2 end = i + l2 //2 return s[start: end + 1 ] def test_main(): sobj = Solution() s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" result = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" assert sobj.longestPalindrome(s) == result
e5649d2b70a4c7a3e4683d58e11b9a975dad9a3f
hatsem78/practica_python
/ejercicios.py
601
3.828125
4
import math def anagrama(word, word2): word = sorted(word) word2 = sorted(word2[::-1]) if word == word2: return True else: return False print(print(anagrama('fresa', 'frase'))) def es_polidromo(word): polidromo = word[::-1] if word == polidromo: return True else: return False print(es_polidromo('ana')) print(es_polidromo('arenera')) print(es_polidromo('mama')) def factorial(number): fac = 1 for element in range(1, number + 1): fac *= element return fac print(math.factorial(5)) print(factorial(5))
14db37534f2757c428b5d99eb638d845c077fc01
harshalms/python
/basics/minimum_difference.py
743
4.1875
4
'''GeeksForGeeks Find minimum difference between any two elements Given an unsorted array, find the minimum difference between any pair in given array. Examples : Input : {1, 5, 3, 19, 18, 25}; Output : 1 Minimum difference is between 18 and 19 Input : {30, 5, 20, 9}; Output : 4 Minimum difference is between 5 and 9 Input : {1, 19, -4, 31, 38, 25, 100}; Output : 5 Minimum difference is between 1 and -4 ''' def minDifference(A): A.sort() mini = max(A) for i in range(len(A)-1): diff = A[i+1] - A[i] mini = min(mini, diff) return mini if __name__ == "__main__": A = [[1, 5, 3, 19, 18, 25], [30, 5, 20, 9], [1, 19, -4, 31, 38, 25, 100]] for i in range(len(A)): print(minDifference(A[i]))
699b703705e6717dd00c0abb1603fceeb8643d73
biocatalytic-coatings/pythonScripts
/millis.py
323
3.546875
4
import time from datetime import datetime, timedelta interval=1 start_time=datetime.now() future_time=start_time + timedelta(seconds=60) dt=datetime.now() print("Started @",dt) while (dt < future_time): #time.sleep(interval) #print("Millis = ",dt) dt=datetime.now() print ("Finished @", datetime.now())
5a6c664bc424dd41516b94535695105b1e3a9ec6
codeAligned/coding-practice
/practicepython.org/exercise20.py
930
3.640625
4
#!/usr/bin/env python3 import random def binarySearch(value, sample, start, end): if start > end: return -1 midIndex = int((start+end) / 2) if value == sample[midIndex]: return midIndex elif value < sample[midIndex]: return binarySearch(value, sample, start, midIndex - 1) else: return binarySearch(value, sample, midIndex + 1, end) sample = [x for x in range(100)] value = random.randint(0, 150) position = binarySearch(value, sample, 0, len(sample) - 1) print(str(value) + ' is found at index ' + str(position)) import time print('Python in vs binartSearch time.') startTime = time.time() if 20 in sample: pass endTime = time.time() print('Total time for in: ' + str((endTime - startTime) * 1000000)) startTime = time.time() binarySearch(20, sample, 0, len(sample) - 1) endTime = time.time() print('Total time for binary: ' + str((endTime - startTime) * 1000000))
3e3f213b14d53a92f3f32a04a2913419b9a7e590
mantripat/python_programs
/palindrome.py
402
3.90625
4
#s1=input("enter any string to check if it is palindrome:") """ s1="maddsam" print("reverse string=",s1[::-1]) if s1[0:]==s1[::-1]: print("String is palindrome") else: print("Its not plaindrome") """ s="hi ! my name is Alpha ..... u can write it like @lph@ 123%%%6&8^%$#" s2="" for i in range(len(s)): if s[i].isalnum() or s[i].isspace(): s2+=s[i] print("new string is \t", s2)
db13bfc35fdca90f2f7d1021fae1de47fca651e2
Zahidsqldba07/competitive-programming-1
/Leetcode/August Leetcoding Challenge/vertical_order.py
1,569
4.0625
4
# Vertical Order Traversal of a Binary Tree ''' Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates). If two nodes have the same position, then the value of the node that is reported first is the value that is smaller. Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: dic = defaultdict(list) self.min_l, self.max_l = float("inf"), -float("inf") def dfs(root, lvl_h, lvl_v): self.min_l = min(lvl_h, self.min_l) self.max_l = max(lvl_h, self.max_l) dic[lvl_h].append((lvl_v, root.val)) if root.left: dfs(root.left, lvl_h - 1, lvl_v + 1) if root.right: dfs(root.right, lvl_h + 1, lvl_v + 1) dfs(root, 0, 0) res = [] for i in range(self.min_l, self.max_l + 1): res += [[j for i, j in sorted(dic[i])]] return res
4bdc92c7596158a48862c14f9cced649638575ab
dhootha/nGramBabbler
/Babbler.py
4,282
3.828125
4
# Babbler: reads in a corpus and uses conditional probabilities to # write out a string of words, with each word generated based off of # the probability that it occurred after the previous n words in the corpus. # # Boyang Niu # [email protected] # 11-13-2013 # # import random import collections class Babbler(object): def __init__(self, filename, ngram_count): """ Populates the dictionary of word counts that make up the babbler with counts based on [ngram_count] previous words when given a [filename] file that acts as a corpus. """ word_table = {} phrase_counts = {} totalwords = 0 # deque automatically evicts the first entry when over maxlen tempwords = collections.deque(maxlen=ngram_count) with open(filename) as f: for line in f: for word in line.strip().split(" "): word = word.lower() # if this is the first word in the corpus if not len(tempwords) == ngram_count: tempwords.append(word) continue # otherwise we use the previous words to generate the next tempword = " ".join(tempwords) if tempword not in word_table: word_table[tempword] = {} phrase_counts[tempword] = 1 else: phrase_counts[tempword] += 1 # add counts to the word table if word not in word_table[tempword]: word_table[tempword][word] = 1 else: word_table[tempword][word] += 1 # add the current word to the previous words and evict one tempwords.append(word) # add to the total count of words totalwords += 1 self.total_words = totalwords self.word_table = word_table self.ngram_size = ngram_count self.phrase_counts, self.phrase_sum = self.generate_list_for_rng( phrase_counts) def get_frequencies(self, words): """ Given a list of words, gives back a list of tuples of (float frequencies, string word) that dictate the probabilities of the next word. """ if words not in self.word_table: return [] return {word2: (float(self.word_table[words][word2]) / sum(self.word_table[words].values())) for word2 in self.word_table[words]} def generate_next_word(self, words): """ Given the words that have already occurred, generate the next word. """ # truncate the word list to the given number of ngrams of this babbler trunc_words = " ".join(" ".join(words).split(" ")[-1 * self.ngram_size:]) # if we encounter a string that we haven't ever seen, generate random if trunc_words not in self.word_table: return self.generate_random_word() # generate the number that we use to pick the next word rng_table, rng_sum = self.generate_list_for_rng( self.get_frequencies(trunc_words)) rng_num = random.random() * rng_sum for freq, word in rng_table: if rng_num > freq: continue else: return word def generate_random_word(self): # partial dict for holding values temporarily rng_num = random.random() * self.phrase_sum for freq, word in self.phrase_counts: if rng_num > freq: continue else: return word def generate_list_for_rng(self, rng_dict): """ Takes a dictionary from word to word count and returns a tuple (a list of tuples from word frequency to word, sum of frequencies) """ # rng_table is a list of tuples (freq, word) of probabilities rng_table = [] rng_sum = 0 for v in rng_dict: rng_sum += rng_dict[v] rng_table.append((rng_sum, v)) return rng_table, rng_sum
2f992cfead04dfcddcd717a63c9eb512b4617d31
daniel-reich/turbo-robot
/QN4RMpAnktNvMCWwg_12.py
961
4.375
4
""" An identity matrix is defined as a square matrix with **1s** running from the top left of the square to the bottom right. The rest are **0s**. The identity matrix has applications ranging from machine learning to the general theory of relativity. Create a function that takes an integer `n` and returns the identity matrix of `n x n` dimensions. For this challenge, if the integer is negative, return the mirror image of the identity matrix of `n x n` dimensions.. It does not matter if the mirror image is left-right or top-bottom. ### Examples id_mtrx(2) ➞ [ [1, 0], [0, 1] ] id_mtrx(-2) ➞ [ [0, 1], [1, 0] ] id_mtrx(0) ➞ [] ### Notes Incompatible types passed as `n` should return the string `"Error"`. """ def id_mtrx(n): if type(n)!=int: return 'Error' else: lst= [[1 if x==y else 0 for y in range(abs(n))]for x in range(abs(n))] return lst if n>0 else lst[::-1]
3b5f2c02635ce0a3f0a9bf38ae5d2cea625e475a
gabriellaec/desoft-analise-exercicios
/backup/user_035/ch37_2020_03_23_23_14_07_056409.py
168
3.890625
4
Senha = False resposta = input("Qual é a senha") while Senha: if resposta!="desisto": print("tenta denovo") else: Senha = True print("Você acertou a senha!")
cfd1bf81e1e7b6c0e8c8c5c8845627f963bd3e15
jakehoare/leetcode
/python_1_to_1000/812_Largest_Triangle_Area.py
961
3.9375
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/largest-triangle-area/ # You have a list of points in the plane. Return the area of the largest triangle that can be formed by any # 3 of the points. # For each 3 points, use shoelace formula as per https://en.wikipedia.org/wiki/Shoelace_formula to calculate area. # Time - O(n**3) # Space - O(1) class Solution(object): def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ n = len(points) largest = 0 for i in range(n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): x1, y1 = points[i] x2, y2 = points[j] x3, y3 = points[k] area = 0.5 * abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) largest = max(largest, area) return largest
9eba62f84d960868a5b699765b204f4f0047eb64
passion4energy/Elyane
/losses/multi_class_cross_entropy.py
972
3.671875
4
""" The Multi-Class Cross-Entropy Loss Function """ import numpy as np from .loss import Loss class MultiClassCrossEntropy(Loss): """ The Multi-class CrossEntropy that contains everything needed to calculate the loss. """ def fct(self, labels, preds): """ The loss function formula. Args: labels (array): The true labels of our dataset. preds (array): The predictions made by our neural networ. Returns: array: Returns the loss according to A and Y. """ return - np.sum(labels * np.log(preds)) def deriv(self, labels, preds): """ Calculates the derivative of the CrossEntropy loss function. Args: labels (array): The true labels of our dataset. preds (array): The predictions made by our neural network. Returns: array: Returns the derivative loss according to A and Y. """ return preds - labels
6bf953d8ba77379b13fd0162be89c54d3ac31e56
dingshuangdian/lsqPython
/day2/format.py
601
3.96875
4
# 格式化输出 # %s d name = input('请输入姓名:') age = input('请输入年龄:') height = input('请输入身高:') job = input('请输入工作:') hobbie = input('你的爱好:') # msg = "我叫%s,今年%s 身高%s" % (name, age, height) msg = '''-------------info of %s -------------- Name:%s age:%s height:%s job:%s hobbie:%s 学习进度为:3%% ''' % (name, name, age, height, job, hobbie) print(msg) # while else count = 0 while count <= 5: count += 1 if count == 3: break print("Loop", count) else: print("没被break打断循环正常执行完成!")
d8f3de21f3aa99da8c9d894ba048342db39dd486
ThompsonHe/LeetCode-Python
/Leetcode0111.py
1,680
4
4
""" 111. 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。 示例: 给定二叉树[3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最小深度 2. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import collections class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 if not root.left and not root.right: return 1 min_depth = 10 ** 9 if root.left: min_depth = min(self.minDepth(root.left), min_depth) if root.right: min_depth = min(self.minDepth(root.right), min_depth) return min_depth + 1 class Solution1: def minDepth(self, root: TreeNode) -> int: if not root: return 0 if not root.left and not root.right: return 1 queue = collections.deque() queue.append([(root, 1)]) while queue: top, depth = queue.popleft() if not top.left and not top.right: return depth if top.left: queue.append((root.left, depth + 1)) if top.right: queue.append((root.right, depth + 1)) return 0
fa1bc157d60353f35b17187d63444fafd026bd29
jeach27/IPC2_Proyecto1_201903873
/lista.py
2,467
3.90625
4
class Lista: def __init__(self, codigo, nombre, n, m, g): self.codigo = codigo self.nombre = nombre self.n = n self.m = m class Nodo: def __init__(self, Lista=None, next = None): self.Lista = Lista self.next = next class ListaCircular: def __init__(self, head=None): self.head = head self.size = 0 def insertar(self, valor): new_nodo = Nodo(Lista = valor, next = self.head) if self.size == 0: self.head = new_nodo new_nodo.next = self.head else: cur = self.head while cur.next is not self.head: cur = cur.next cur.next = new_nodo new_nodo.next = self.head self.size +=1 def palabra(self): if self.head is None: return aux = self.head palabra='' palabra = palabra + aux.Lista.codigo while aux.next != self.head: aux = aux.next palabra = palabra + aux.Lista.codigo return palabra def imprimir(self): if self.head is None: return Nodo = self.head print('\n'+Nodo.Lista.codigo) while Nodo.next != self.head: Nodo = Nodo.next print( '\n'+Nodo.Lista.codigo) def imprimir1(self): if self.head is None: return Nodo = self.head print('\n'+Nodo.Lista.codigo , end = "=>") while Nodo.next != self.head: Nodo = Nodo.next if Nodo.next == self.head: print(Nodo.Lista.codigo+'\n') else: print( Nodo.Lista.codigo , end = "=>") def ultimo(self): if self.head is None: return Nodo = self.head while Nodo != self.head: if Nodo.next == self.head: return Nodo.Lista.codigo def eliminar(self, dato): if self.head is None: return elif dato == self.head.Lista.codigo: Nodo = self.head while Nodo.next != self.head: Nodo = Nodo.next Nodo.next = self.head.next self.head = self.head.next else: Nodo = self.head pre = None while Nodo.Lista.codigo != dato: pre = Nodo Nodo = Nodo.next pre.next = Nodo.next
7c5b6f7faa46e2c99e469729e22227e0b9104227
kimgy0/Python_Practice
/CLASS/10_7_Polymorphism.py
535
4.1875
4
class Animal: def __init__(self,name): self.name=name def talk(self): raise NotImplementedError("Subclass must implement abstract method") #해당 자식 객체를 제외한 다른 클래스가 이 메서드를 쓰지 못하게 함. class Dog(Animal): def talk(self): return "woof! woof!" class Cat(Animal): def talk(self): return "meow!" animals=[Cat("missy"),Dog("mistoffelees"),Cat("lassie")] for animal in animals: print(animal.name,":",animal.talk())
2f4642e62b7b9739a119763968ef0e5a1acab35e
guoweifeng216/python
/python_design/pythonprogram_design/Ch5/5-1-E35.py
436
3.96875
4
def main(): ## Display the largest number in the file Numbers.txt max = getMax("Numbers.txt") print("The largest number in the \nfile Numbers.txt is", str(max) + ".") def getMax(fileName): infile = open("Numbers.txt", 'r') max = int(infile.readline()) for line in infile: num = int(line) if num > max: max = num infile.close() return max main()
89e2eb44c6a27362d91c2b349f35f3b781891f42
Django-Lessons/lesson-41-argparse-module
/draw.py
1,620
3.921875
4
import argparse CIRCLE = 'circle' SQUARE = 'square' class Square: def __init__(self, p1, p2): print("Square") class Circle: def __init__(self, p1, radius): print(f"Circle center=({p1[0]}, {p1[1]}) radius={radius}") def circle_func(args): Circle(args.center, args.radius) def square_func(args): Square(args.point1, args.point2) def handle_circle_args(subparsers): parser = subparsers.add_parser(CIRCLE) parser.add_argument( "radius" ) parser.add_argument( "-c", "--center", nargs=2, help="Center of the circle", default=(0, 0), metavar=("x", "y") ) parser.set_defaults(func=circle_func) def handle_square_args(subparsers): parser = subparsers.add_parser(SQUARE) parser.add_argument( "-p1", "--point1", nargs=2, help="Upper left coordinate, specified as X Y", default=(0, 0), metavar=("x", "y") ) parser.add_argument( "-p2", "--point2", nargs=2, help="Lower right coordinate, specified as X Y", default=(600, 600) ) parser.set_defaults(func=square_func) def main(): parser = argparse.ArgumentParser() parser.add_argument( '-o', '--optimize', action="store_true", default=False ) subparsers = parser.add_subparsers() handle_circle_args(subparsers) handle_square_args(subparsers) args = parser.parse_args() args.func(args) if args.optimize: print("Optimized algorithm") else: print("...") if __name__ == '__main__': main()
34007ec1cc22bbc359d08c5d553c45e1d55f80a6
logan-lach/Algos
/max_contiguous_sum/kadanes.py
2,740
3.84375
4
def kadanes_1(A): # Whoohoo! this is the alt branch! total = gcs_value = A[0] total_list = [A[0]] gcs = [A[0]] for i in range(1, len(A)): ''' The opening step. Our combination between everything we seen this far and our new item We will check if this contributes something to our growth, we will see shortly ''' t = total + A[i] ''' So, if the combination of everything we have so far is greater than the item itself WHAT THIS CAN BE THOUGHT OF IS 'Does the rest of the list weigh this item down?' ''' if t > A[i]: ''' If it doesn't weight it down, then our biggest out of the current items we have seen is just the conglomeration of all the items so far. We will adjust both our current total and total_list to account for this ''' total = t total_list += [A[i]] else: ''' Else if the rest of the list DOES hold our current item back(more negatives than positives) WE NO LONGER HAVE TO CONSIDER THAT PART OF OUR ARRAY AS BEING THE MAX, SO we leave it behind in the dust and start anew at our newest member ''' total = A[i] total_list = [A[i]] ''' Now, here's the mac daddy step Throughout it all, we collect our greatest array up to our index i. This array will always grow throughout every iteration, as to gauge if our previous list helps/hurts the cause Now, this is where A[i] gets gauged. We previously only checked if the rest of the list helped/hurt our total. If it didn't, we added A[i] to the list with no questions asked Now, if adding A[i] HURT THE TOTAL, our variable total will feel it. As such, when we assigned total to our total += A[i] in our previous step, and engage in our comparison now, A[i] will have been revealed to have lowered the total, and therefore the addition to A[i] cannot be greater than the gcs_value This also helps differentiate between our i-sized list and the actual max. Just because we have added some positive numbers to our total, does that really mean it outweighs the negatives you have picked up so far? The negatives will always be picked up as long as we don't hit a A[i] that is greater than our previous list. We have to be mindful of that when considering the real gcs_value ''' if total > gcs_value: gcs_value = total gcs = total_list[:] return gcs print(kadanes_1([1,3,-5,2,3]))
cebb81f80c0a4f307b9e752723001df4b7a0055d
GKPSingh/Functions-Practice
/siminterest.py
173
3.625
4
# Python Program for simple interest def si(p, r, t): simple_interest = (p * r * t)/100 print(f'The value of simple interest is {simple_interest}') si(100, 10, 1)
f42e5e6e0a1ea2789493606a517180446e6c6d9f
Nirali0029/Algorithms-in-python
/Algorithms/Sorting/selection_sort.py
216
3.578125
4
def selection(a): n=len(a) for i in range(n): min=i for j in range(i,n): if a[j]<a[min]: min=j if i!=min: a[i],a[min]=a[min],a[i] return a a=[2,7,4,6,1,8,5] print(selection(a))
f553a41fac58e9cca0b4dccbf7317b29df55ce00
RohanDeySarkar/DSA
/linked_lists/linked_list_palindrome/linkedListPalindrome.py
965
3.828125
4
# This is an input class. Do not edit. class LinkedList: def __init__(self, value): self.value = value self.next = None # Recursion def linkedListPalindrome(head): isEqual, _ = isPalindrome(head, head) return isEqual def isPalindrome(leftNode, rightNode): if rightNode is None: return (True, leftNode) nodesAreEqual, leftNodeToCompare = isPalindrome(leftNode, rightNode.next) isEqual = nodesAreEqual and leftNodeToCompare.value == rightNode.value return (isEqual, leftNodeToCompare.next) # Reverse linkedList check def linkedListPalindrome(head): reverseListHead = reverseLinkedList(head) while head is not None and reverseListHead is not None: if head.value != reverseListHead.value: return False head = head.next reverseListHead = reverseListHead.next return True def reverseLinkedList(head): prev = None while head is not None: temp = head.next head.next = prev prev = head head = temp return prev
1a72ce540701c897939e3a1339dcdf4de0adf631
amiraHag/python-basic-course2
/database/database3.py
1,165
3.71875
4
# ------------------------------------------------------ # -- Databases => SQLite => Insert Data Into Database -- # ------------------------------------------------------ # - cursor => All Operation in SQL Done By Cursor Not The Connection Itself # - commit => Save All Changes # ------------------------------------------------------ # Import SQLite Module import sqlite3 # Create Database And Connect db = sqlite3.connect("app.db") # Setting Up The Cursor cr = db.cursor() # Create The Tables and Fields cr.execute("create table if not exists users (user_id integer, name text)") cr.execute( "create table if not exists skills (name text, progress integer, user_id integer)") #Inserting Data cr.execute("insert into users(user_id, name) values(1, 'Amira')") cr.execute("insert into users(user_id, name) values(2, 'Ahmed')") cr.execute("insert into users(user_id, name) values(3, 'Sara')") # my_list = ["Ahmed", "Amira", "Sara", "Fatema", "Aya", "Mohamed", "Omar"] # for key, user in enumerate(my_list): # cr.execute(f"insert into users(user_id, name) values({key + 1}, '{user}')") # Save (Commit) Changes db.commit() # Close Database db.close()
927122669494c4c749257820ff4f0ae734eb1b4a
WebDevExpertise/Notes_For_Python
/unit_4/lecture_4.py
1,865
4.59375
5
# Unit 4: For Loops, Working with Lists & Other Ways of Storing Mutliple Pieces of Information # 4.1 - 4.2 - Using For Loops on Lists movies = ['Avengers: End Game', 'Ralph Breaks the Internet'] for movie in movies: print(movie) # prints "Avengers: End Game", and "Ralph Breaks the Internet" in seperate lines onto the console/terminal # 4.3 - Using For Loops to "get from point A to point B" for i in range(5, 11): print(i) # prints numbers 5-10 onto the console/terminal # 4.4 & 4.5 - Creating a List Based on Ranges numbers = list(range(1, 6)) for num in numbers: print(num) # prints numbers 1-5 onto the console/terminal print(min(numbers)) # executes after the for loop is done iterating over the list print(max(numbers)) # executes after the print(min(numbers)) runs print(sum(numbers)) # prints the sum of all of the numbers in the list # 4.6 - Finding Even or Odd Numbers in a Range for even_num in range(0, 15, 2): print(even_num) # prints all the even numbers that fall between 0 (inclusive) & 15 (exclusive) # 4.7 - Cubing Numbers Within a Range for cubed_num in range(10, 21): print(cubed_num ** 3) # prints every number ranging from 10 (inclusive) to 21 (exclusive) cubed onto the console/terminal # 4.8 - Printing More Than One Item From a List candies = ['hershey', 'snickers', 'twix', 'milky way'] print(f'My favorite candies are {candies[slice(2)]}') # prints "My favorite candies are ['hershey', 'snickers']" onto the console/terminal # 4.9 - Using Tuples cars = ('bmw', 'ferrari', 'lamborghini', 'volkswagen') print(cars) # prints ('bmw', 'ferrari', 'lamborghini', 'volkswagen') onto the console/terminal print(cars[1]) # prints "ferrari" onto the console/terminal for car in cars: print(car) # prints "bmw", "ferrari", "lamborghini", "volkswagen" onto the terminal/console
9c48662077fcc74d7382c74f218cea427d110f10
moeburney/2040
/scripts/classes/colors.py
1,172
3.6875
4
''' Created on Jul 14, 2011 @file: colors.py @author: jake bolton Usage: Feel free to use code as you want! functions: random_color(search=None): search_color(name) ''' import pygame from pygame.locals import * from pygame.color import THECOLORS from random import choice VERSION = '0.1' # def random_color(search=None): """get a single random Color(), with Optional search filter. search='green' will return 'seagreen', 'bluegreen', etc... default to choice() of full list""" if search: c = choice(search_color(search)) else: c = choice(THECOLORS.values()) #debug: print type(c), c # returns Color() return c #todo: exception on color search fail? OR just default to white. def search_color(name): """search pygame. THECOLORS for a name, example: "green" -> seagreen, bluegreen, darkgreen """ #verbose: print "search_color( {} ) =".format(name) return [Color(c) for c in pygame.color.THECOLORS if name in c] # for search* color_groups = ['', 'white', 'purple','green','dark','light','red','blue','orange','gray','blue','green']
e12db07f662918cc36ac39f7f006448fd56e1558
JoMOlsson/neural_playground
/ANNet.py
39,935
3.609375
4
import numpy as np from math import e import matplotlib.pyplot as plt import mnist import math from colour import Color from PIL import Image import copy import os import glob import random def sigmoid(z): """ Calculates the output of the sigmoid function from the provided z-data :param z: (float, int, npArray) Input data :return g: Output of sigmoid function """ g = 1 / (1 + e**(-z)) return g def sigmoid_gradient(z): """ Calculates the output of the sigmoid derivative function from the provided z-data :param z: (float, int, npArray) Input data :return g: Output of sigmoid derivative function """ g = sigmoid(z)*(1 - sigmoid(z)) return g class ANNet: def __init__(self): self.default_hidden_layer_size = 15 # Default number of neurons in hidden layer self.epsilon = 0.12 # Initialization value for weight matrices self.alpha = 1.0 # Learning rate self.network_size = [] # Default network size self.Theta = [] # Holding weight matrices self.feature_mean_vector = [] # (list) average values in data per feature self.feature_var_vector = [] # (list) variance values in data per feature self.data_min = None # (float) min value in input data self.feature_min_vector = [] # (list) min values in data per feature self.data_max = None # (float) max value in input data self.feature_max_vector = [] # (list) max values in data per feature self.num_of_train_samples = None # (int) Number of train samples self.input_shape = [] # Original shape of input data self.num_of_test_samples = None # (int) Number of labels in test data-set self.train_data = np.array([]) # Hold train data self.test_data = np.array([]) # Holds test data self.train_labels = [] # Labels for train-data self.test_labels = [] # Labels for test-data self.output_layer_size = [] # Output layer size self.input_layer_size = None # Input layer size self.network_architecture = None # Network architecture self.gif_created = False # Boolean variable if gif was ever created self.is_mnist = False # Boolean variable stating if mnist data-set is used self.orig_images = [] # List holding the original images self.orig_test_images = [] # List holding the original test images def init_network_params(self, network_size): """ Takes a list of integers and assigns it to the network_size class variable and creates the weight matrices (theta) corresponding to the network architecture. The weights of the artificial network will be initialized to random values in the interval (-self.epsilon, self.epsilon) :param network_size: (list) :return theta: (list) List of npArrays containing the network weights """ theta = [] self.network_size = network_size for i in range(0, len(network_size)-1): n = (network_size[i]+1) * network_size[i+1] t = np.random.uniform(-self.epsilon, self.epsilon, size=(1, n)) theta.extend(t) self.Theta = theta return theta @staticmethod def create_gif(): """ Will fetch all *.png files located under the temp folder and creates an animated gif to visualize the training sequence. :return: """ print("Creating gif ... ") cur_path = os.path.dirname(os.path.realpath(__file__)) temp_path = os.path.join(cur_path, 'temp') image_directory = glob.glob(temp_path + '/*.png') images = [] i = 0 for im_dir in image_directory: print(str(i/len(image_directory))) if i < 1000: images.append(Image.open(im_dir)) i += 1 print("Images loaded") images[0].save('movie.gif', save_all=True, append_images=images) def set_network_architecture(self, network_architecture): """ Assigns the provided network_architecture variable to the internal class-variable self.network_architecture :param network_architecture: (list) List of integer corresponding to the desired size of the input layer, hidden layers and the output layer. :return: """ self.network_architecture = network_architecture def set_mnist_data(self): """ Imports the mnist data-set and assigns it to the train- & test-data. The mnist data-set is an open source data set consisting of 60000 training images of hand-written digits. The method will also assign the internal class-variable self.is_mnist to true. :return: """ # Extract data train_images = mnist.train_images() train_labels = mnist.train_labels() test_images = mnist.test_images() test_labels = mnist.test_labels() self.orig_images = train_images self.orig_test_images = test_images # Assign data self.set_train_data(train_images) self.set_train_labels(train_labels) self.set_test_data(test_images) self.set_test_labels(test_labels) self.is_mnist = True def normalize_data(self, data): """ Takes the provided data and normalize it using the min and the max values of the data. If the min and max is already provided, the stored max/min value will be used. :param data: (npArray) Numpy array corresponding to the data to be used within the neural network :return data: (npArray) Normalized data """ data = np.array(data) data = data.astype('float64') # Assign mean and var vector if not available if 'self.feature_mean_vector' not in locals(): feature_mean_vector = [] for iFeat in range(0, data.shape[1]): feature_mean_vector.append(np.mean(data[:, iFeat])) self.feature_mean_vector = feature_mean_vector if 'self.feature_var_vector' not in locals(): feature_var_vector = [] for iFeat in range(0, data.shape[1]): feature_var_vector.append(np.var(data[:, iFeat])) self.feature_var_vector = feature_var_vector if 'self.feature_min_vector' not in locals(): self.data_min = np.min(np.min(data)) feature_min_vector = [] for iFeat in range(0, data.shape[1]): feature_min_vector.append(np.min(data[:, iFeat])) self.feature_min_vector = feature_min_vector if 'self.feature_max_vector' not in locals(): self.data_max = np.max(np.max(data)) feature_max_vector = [] for iFeat in range(0, data.shape[1]): feature_max_vector.append(np.max(data[:, iFeat])) self.feature_max_vector = feature_max_vector # ----- Normalize data ----- for iData in range(0, data.shape[0]): d = np.array(data[iData, :]) d_norm = (2*(d - self.data_min)) / (self.data_max - self.data_min) - 1 data[iData, :] = d_norm return data def set_train_data(self, data): """ Assigns the provided data to the training data-set. The data will be normalized using the normalize_data method. The method will also assign the class variables input_layer_size, num_of_train_samples, input_shape based on the properties of the provided data. :param data: (npArray) Data to be set to the training data-set :return: """ train_data = [] if len(data.shape) == 3: self.input_layer_size = data.shape[1] * data.shape[2] self.num_of_train_samples = data.shape[0] self.input_shape = [data.shape[1], data.shape[2]] # Reshape data for i in range(0, len(data)): train_data.append(np.array(np.matrix.flatten(data[i]))) elif len(data.shape) == 2: self.input_layer_size = data.shape[1] self.num_of_train_samples = data.shape[0] self.input_shape = [1, data.shape[1]] train_data = data train_data = self.normalize_data(np.array(train_data)) self.train_data = train_data def set_test_data(self, data): """ Assigns the provided data to the test data-set. The data will be normalized using the normalize_data method. The method will also assign the class variables input_layer_size, num_of_train_samples, input_shape based on the properties of the provided data. :param data: (npArray) Either a numpy array or list with test samples :return: """ test_data = [] self.num_of_test_samples = data.shape[0] if len(data.shape) == 3: self.input_shape = [data.shape[1], data.shape[2]] # Reshape data for i in range(0, len(data)): test_data.append(np.matrix.flatten(data[i])) elif len(data.shape) == 2: self.input_shape = [1, data.shape[1]] test_data = self.normalize_data(np.array(test_data)) self.test_data = np.array(test_data) def set_train_labels(self, labels): """ Assigns the provided labels to the labels of the training data-set. The method will also set the class-variable output_layer_size based on the unique set of labels in the provided data. :param labels: (npArray/list) Either a numpy array or list with labels corresponding to the true classifications of the training data-set :return: """ self.train_labels = labels if 'self.output_layer_size' not in locals(): self.output_layer_size = len(np.unique(labels)) def set_test_labels(self, labels): """ Assigns the provided labels to the labels of the test data-set. The method will also set the class-variable output_layer_size based on the unique set of labels in the provided data. :param labels: (npArray/list) Either a numpy array or list with labels corresponding to the true classifications of the training data-set :return: """ self.test_labels = labels if 'self.output_layer_size' not in locals(): self.output_layer_size = len(np.unique(labels)) def forward_propagation(self, x, y=None): """ Will make predictions by forward propagate the provided input data x through the neural network stored in within the class. If the annotations (labels) are provided through the y-input variable, the cost (c) of the network will be calculated post the forward propagation using the least-square method. Else the cost will be set to None. Along with the predictions (h) per provided samples and the total cost (c), the method will return a list of all activation layers (a_list) and a list of all sigmoid layers (z_list) :param x: (npArray) Input data to be propagated through the neural network, Either one ore more samples. :param y: (npArray) [optional] Annotations to be used to calculate the network cost :return h, (npArray) Prediction array c, (float) Network cost a_list, (list) List of all activation layers z_list: (list) List of sigmoid layers """ num_of_samples = len(x) if len(x.shape) > 1 else 1 # Sets the number of samples based on the dimensions of the # provided input data (x) bias = np.ones((num_of_samples, 1)) # Create bias units a = x # Sets first activation layer to the provided input data a_list = [] # List containing all activation in the forward propagation if num_of_samples > 1: a = np.vstack([bias.T, a.T]) a = a.T else: a = np.append(bias, a) a_list.append(a) z_list = [] # List to hold all sigmoid values for i, theta in enumerate(self.Theta): # Forward propagate through all layers t = theta.reshape(self.network_size[i]+1, self.network_size[i+1]) # Reshape parameter matrix z = np.matmul(a, t) # z = a*t z_list.append(z) # Store the sigmoid values a = sigmoid(z) # Calculate the activation layer # add bias unit if num_of_samples > 1: a = np.column_stack([bias, a]) else: a = np.append(bias, a) a_list.append(a) # Store activation layer h = a # Prediction layer is equal to the final activation layer # pop bias unit if len(h.shape) > 1: h = h[:, 1:] else: h = h[1:] a_list.pop(-1) # Last layer in a is equivalent to h # Calculate cost (Least Square Method) if y is None: # labels has not been provided, cost can not be calculated c = None else: c = (1 / (2 * num_of_samples)) * np.sum((h - y) ** 2) # Cost with LSM return h, c, a_list, z_list def draw_and_predict(self): """ The method will randomly pick a sample in the test data-set and makes a prediction by doing a forward propagation using the current state of the neural network. If the network data is the mnist data-set the drawn sample will be visualised and the predicted value will be printed. :return: """ sample_idx = random.randint(0, self.test_data.shape[0]) x = self.test_data[sample_idx, :] y = self.test_labels[sample_idx] y_hat = np.zeros((self.output_layer_size, 1)) y_hat[y] = 1 h, c, a, z = ANNet.forward_propagation(self, x, y_hat) prediction = np.argmax(h) print("Network predicts value: " + str(prediction)) im = x.reshape(self.input_shape[0], self.input_shape[1]) plt.imshow(im) plt.show() def train_network(self, x=None, y=None, num_of_iterations=1000, visualize_training=True): """ The method will initialize a training session with a number of training iterations determined by the variable num_of_iterations (int). The network will be trained using the x data as input data and the y data as the annotations. If x or y are not provided the input data and the annotation data will be set to the internal class-variables self.train_data and self.train_labels. The network is trained by forward propagating the input data and then back propagate the errors using gradient decent. If the boolean variable visualize_training is set to true, the training session will be visualized and the output will be stored in a temp-folder under the current directory path. :param x: (npArray) Input data to be propagated through the network :param y: (npArray) Training labels used for calculating the network errors for back-propagation :param num_of_iterations: (int) Number of iterations to be executed in the training session :param visualize_training: (boolean) Boolean flag to indicate if the training session should be visualized :return: """ historic_prediction = [] # holds the predicted values for every iteration, used for visualization historic_theta = [] # holds the wight matrices for every iteration, used for visualization # Set input and label data if not provided if (x is None) or (y is None): x = self.train_data y = self.train_labels num_of_samples = len(x) # Samples in the training set # Initialize weights if they have not been initialized by user. if not self.Theta: if self.network_architecture is None: print("Network weights has not been initialized by user!, default hidden layer of size " + str(self.default_hidden_layer_size) + " has been applied") input_layer_size = self.input_layer_size output_layer_size = self.output_layer_size network_architecture = [input_layer_size, self.default_hidden_layer_size, output_layer_size] self.network_architecture = network_architecture self.init_network_params(self.network_architecture) # Preparing label data, every sample will be represented by a vector with the size equal to the number of # unique classes in the training data. The correct classification will be marked by a one while the false # classifications are marked with a zero for all samples. The label matrix will be of the size # [num_of_train_samples x num_of_unique_classes] y_mat = np.zeros((y.shape[0], self.output_layer_size)) for i, val in enumerate(y): y_mat[i][int(val)] = 1 cost = np.zeros([num_of_iterations, 1]) # Holding cost value per iteration accuracy = np.zeros([num_of_iterations, 1]) # Holding accuracy value per iteration for iteration in range(0, num_of_iterations): # Init weight gradient matrices theta_grad = [] for iLayer, theta in enumerate(self.Theta): theta = theta.reshape(self.network_size[iLayer]+1, self.network_size[iLayer+1]) theta_grad.append(np.zeros(theta.shape)) h_mat, c, a_mat, z_mat = ANNet.forward_propagation(self, x, y_mat) # Forward propagate delta = -(y_mat-h_mat) for iLayer in range(len(a_mat)-1, -1, -1): z = z_mat[iLayer] if not iLayer == len(a_mat)-1: index = iLayer + 1 theta = self.Theta[index] t = theta.reshape(self.network_size[index] + 1, self.network_size[index + 1]) t = t[1:, :] delta_weight = np.dot(t, delta.T) sig_z = sigmoid_gradient(z) delta = delta_weight * sig_z.T delta = delta.T else: delta = delta * sigmoid_gradient(z) a = a_mat[iLayer] th_grad = np.dot(a.T, delta) theta_grad[iLayer] += th_grad # Update weights from the weight gradients for i, theta_val in enumerate(theta_grad): theta_grad[i] = (1/num_of_samples)*theta_val t = self.alpha * theta_grad[i] self.Theta[i] -= t.flatten() # Save the weight values for animation historic_theta.append(copy.deepcopy(self.Theta)) # Calculate and print cost h, c, _, _ = ANNet.forward_propagation(self, x, y_mat) historic_prediction.append(h) itr = 0 num_of_errors = 0 for p in h: prediction = np.argmax(p) y = np.argmax(y_mat[itr]) if not prediction == y: num_of_errors += 1 itr += 1 # ------------------------------ print iteration -------------------------------- cost[iteration] = c accuracy[iteration] = 1 - num_of_errors/num_of_samples print("Iteration (" + str(iteration) + "/" + str(num_of_iterations) + "), " + "Cost of network: " + str(c) + " , number of false predictions: " + str(num_of_errors) + " , accuracy: " + str(1 - num_of_errors/num_of_samples)) if visualize_training: # # ===== Dump data to json ===== picture_idx = random.randint(0, len(self.test_labels)) h_test, c_test, a_test, z_test = ANNet.forward_propagation(self, self.test_data[picture_idx, :], self.test_labels[picture_idx]) picture = self.orig_test_images[picture_idx, :, :] # create dump json file cur_path = os.path.dirname(os.path.realpath(__file__)) data_path = os.path.join(cur_path, 'data_dump') if not os.path.exists(data_path): # Create dump folder os.makedirs(data_path) else: # clean dump folder for file in glob.glob(os.path.join(data_path, '*.npy')): os.remove(file) # Dump data data = {'picture': picture, 'theta': self.Theta, 'network_size': self.network_size, 'a': a_test, 'z': z_test, 'prediction': h_test} np.save(os.path.join(data_path, 'data.npy'), data) # save to npy file # ----- Plot Cost/Accuracy progression ----- plt.close() plt.plot(cost) plt.plot(accuracy) plt.pause(0.001) plt.ion() plt.show() self.visualize_training(x, cost, accuracy, historic_theta, historic_prediction) def visualize_training(self, x, cost, accuracy, historic_theta, historic_prediction): """ The method will visualize the training session in a (2x2) subplot displaying cost/accuracy, sample predictions and neural network for the whole training session. The output will be stored with .png files stored in a temp folder. :param x: (npArray) Training input data set :param cost: (list) List holding the cost values per iteration :param accuracy: (list) List holding the accuracy values per iteration :param historic_theta: (list) List holding all weight matrices per iteration :param historic_prediction: (list) List holding all predictions for every iteration :return: """ fig, axs = plt.subplots(2, 2) mng = plt.get_current_fig_manager() mng.window.state('zoomed') temp_folder = self.create_temp_folder() # Create a temp-folder to store the training visualisation content # Extract min/max weight absolute_weight = False max_weight = [] min_weight = [] if absolute_weight: max_weight = -np.inf min_weight = np.inf for theta in historic_theta: for t in theta: max_v = np.max(np.max(t)) min_v = np.min(np.min(t)) if max_weight < max_v: max_weight = max_v if min_weight > min_v: min_weight = min_v picture_idx = [] num_of_pics_m = 23 num_of_pics_n = 45 tot_num_of_pics = num_of_pics_m * num_of_pics_n if self.is_mnist: picture_idx = random.sample(range(0, len(self.train_labels)), tot_num_of_pics) image_directory = [] num_of_digits = self.determine_number_of_digits(len(historic_prediction)) for iteration in range(0, len(historic_prediction)): title_str = 'Cost: ' + str(cost[iteration]) + ' , Accuracy: ' + str(accuracy[iteration]) + \ ' , Iteration: ' + str(iteration) fig.suptitle(title_str) print(iteration) h = historic_prediction[iteration] # ----- Prediction plot [0, 0]----- outcome = [] col = [] col_true = [] if self.is_mnist: output_classes = list(set(self.train_labels)) num_of_false_predictions = np.zeros((len(output_classes),), dtype=int) num_of_true_predictions = np.zeros((len(output_classes),), dtype=int) outcome = np.ones((len(h),), dtype=int) for i_sample in range(0, len(h)): y = self.train_labels[i_sample] prediction = np.argmax(h[i_sample, :]) if prediction != y: outcome[i_sample] = 0 num_of_false_predictions[y] += 1 else: num_of_true_predictions[y] += 1 axs[0, 0].bar(output_classes, num_of_false_predictions, color='#ff5959', edgecolor='white') axs[0, 0].bar(output_classes, num_of_true_predictions, color='#34ebd6', edgecolor='white', bottom=num_of_false_predictions) axs[0, 0].set_xlabel('Output classes') axs[0, 0].set_ylabel('Number of false vs number of true') else: for i_sample in range(0, h.shape[0]): col.append('#ff5959' if np.argmax(h[i_sample, :]) else '#34ebd6') col_true.append('#ff5959' if self.train_labels[i_sample] else '#34ebd6') axs[0, 0].scatter(x[:, 0], x[:, 1], c=col) axs[0, 0].axis('equal') axs[0, 0].set_xticks([]) axs[0, 0].set_yticks([]) # ----- Cost / Accuracy plot [1,0] ----- axs[1, 0].plot(cost[0: iteration], label='Cost') axs[1, 0].plot(accuracy[0: iteration], label='Accuracy') axs[1, 0].legend() # ----- Reference plot [0, 1]----- if self.is_mnist: classification_result = outcome[picture_idx] border_thickness = 4 m = self.input_shape[0] + 2*border_thickness n = self.input_shape[1] + 2*border_thickness validation_image = np.zeros((num_of_pics_m * m, num_of_pics_n * n, 3)) def_im = np.zeros((m, n, 3)) # Set frame im_true = def_im.copy() border_color_channel = 1 # Green im_true[0:border_thickness - 1, 0:n, border_color_channel] = 1 # top im_true[m - border_thickness + 1:m, 0:n, border_color_channel] = 1 # right im_true[0:m, 0:border_thickness - 1, border_color_channel] = 1 # left im_true[0:m, n - border_thickness + 1:n, border_color_channel] = 1 # bottom im_false = def_im.copy() border_color_channel = 0 # Red im_false[0:border_thickness - 1, 0:n, border_color_channel] = 1 # top im_false[m - border_thickness + 1:m, 0:n, border_color_channel] = 1 # right im_false[0:m, 0:border_thickness - 1, border_color_channel] = 1 # left im_false[0:m, n - border_thickness + 1:n, border_color_channel] = 1 # bottom idx = 0 for i in range(0, num_of_pics_m): for j in range(0, num_of_pics_n): sample_idx = picture_idx[idx] mnist_im = self.orig_images[sample_idx] if classification_result[idx]: im = im_true else: im = im_false # Set image im[border_thickness:m-border_thickness, border_thickness:n-border_thickness, 0] = mnist_im / 255 im[border_thickness:m - border_thickness, border_thickness:n - border_thickness, 1] = mnist_im / 255 im[border_thickness:m - border_thickness, border_thickness:n - border_thickness, 2] = mnist_im / 255 # ----- Set overall picture ----- validation_image[i*m:(i+1)*m, j*n:(j+1)*n, :] = im idx += 1 axs[0, 1].imshow(validation_image) axs[0, 1].set_xticks([]) axs[0, 1].set_yticks([]) axs[0, 1].set_title(str(round(tot_num_of_pics / len(self.train_labels) * 1000) / 10) + '% of the data') else: axs[0, 1].scatter(x[:, 0], x[:, 1], c=col_true) axs[0, 1].axis('equal') axs[0, 1].set_xticks([]) axs[0, 1].set_yticks([]) # ----- Network plot [1, 1]----- if absolute_weight: self.draw_network(historic_theta[iteration], axs[1, 1], max_weight, min_weight) else: self.draw_network(historic_theta[iteration], axs[1, 1]) # ----- Save figure ----- im_dir = self.append_with_zeros(num_of_digits, iteration) + '.png' im_dir = os.path.join(temp_folder, im_dir) image_directory.append(im_dir) plt.savefig(im_dir) # ----- Clear figures ----- axs[0, 0].clear() axs[0, 1].clear() axs[1, 1].clear() axs[1, 0].clear() plt.close(fig) @staticmethod def create_temp_folder(): """ The method will create a folder called temp in the current file-directory if it already does no exist. If the folder already exists it will flush it by deleting all .png files located in the folder. :return temp_folder: (str) path to temp folder """ current_path = os.path.dirname(os.path.realpath(__file__)) # Get current directory path temp_folder = os.path.join(current_path, 'temp') # Temp folder path if not os.path.exists(temp_folder): os.makedirs(temp_folder) # Create if not already exist # flush folder from png files = os.listdir(temp_folder) # List all files in temp folder for file in files: if file.endswith(".png"): os.remove(os.path.join(temp_folder, file)) # Delete if file is png return temp_folder @staticmethod def determine_number_of_digits(num_of_iterations): """ Determines the number of digits needed in the image naming to hold all iterations. This is used to get the images naturally sorted based on name even in a windows file-explorer. :param num_of_iterations: (int) Total number of iterations :return num_of_digits: (int) Total number of needed digits in the file-naming """ num_of_digits = math.ceil(math.log10(num_of_iterations + 0.001)) return num_of_digits @staticmethod def append_with_zeros(num_of_digits, iteration): """ Will give the file-name of the current iteration. The file will be named to enable natrual sorting even in a windows OS. For instance, if total number of digits == 3 and current iteration is 7 the file-name will be "007" :param num_of_digits: (int) Total number of needed digits in the file-naming :param iteration: (int) Current iteration :return appended_name: (str) File name """ number_of_zeros = num_of_digits - math.ceil(math.log10(iteration + 0.001)) appended_name = '' for i in range(0, number_of_zeros): appended_name += '0' appended_name += str(iteration) return appended_name def draw_network(self, theta, axs, max_weight=None, min_weight=None): """ The method will take list of weight matrices (npArray) and a plot axis and display the the network given by the weight matrices. If the max&min weight values (float) are given, they will be used as max and min for the color scaling of the weight lines, otherwise the the method will use the max and min value in the weight matrices. This is used to enable absolute color scaling through a series of training iterations. The method will display all neurons, along with bias neurons as-well as the weight network between the neurons. The color of the neurons and the weights will be set by their individual values. The method will also display the sum of the network per layer to enable visualisation of changes in the network between iterations. :param theta: (list) List of weight matrices to be displayed :param axs: (matplotlib axes) axis where the figure should be displayed :param max_weight: (float) maximum value used for color scaling :param min_weight: (float) minimum value used for color scaling :return: """ neuron_radius = 1 # Neuron radius neuron_distance = 15 # Distance between neurons in each layer layer_distance = 10 * neuron_distance # Distance between each layer # Reconstruct weight matrices network_architecture = [] i_layer = len(theta) for i_layer, t in enumerate(theta): theta[i_layer] = t.reshape(self.network_size[i_layer] + 1, self.network_size[i_layer + 1]) network_architecture.append(theta[i_layer].shape[0]) network_architecture.append(theta[i_layer].shape[1]) # Calculate position lists use_max_y = True max_y = (max(network_architecture)-1)*(neuron_distance + 2*neuron_radius) x = 0 # x-position of the first neural layer neuron_positions = [] # List holding the positions of all neurons min_y_pos = [] # List holding the minimum y-value for each layer for N_neurons in network_architecture: p = [] # Position list storing the positions of the neurons of the current layer # Find vertical start position if use_max_y: # The width in the y-dimension will be equal for all layers y0 = max_y / 2 delta_y = max_y / (N_neurons - 1) else: # The width in the y-dimension will be different for all layers. The y-positions of the neurons will # distributed according to the neuron_radius and neuron_distance variables if N_neurons % 2: n = math.floor(N_neurons / 2) y0 = (2 * neuron_radius + neuron_distance) * n else: n = N_neurons / 2 y0 = (neuron_distance / 2 + neuron_radius) + (neuron_distance + 2 * neuron_radius) * (n - 1) delta_y = (neuron_distance + 2 * neuron_radius) # Position the neurons of the current layer y = y0 for i in range(0, N_neurons): pos_tuple = (x, y) p.append(pos_tuple) y -= delta_y neuron_positions.append(p) # Store the neuron positions of the current layer x += layer_distance # update the x-position for the new neuron layer min_y_pos.append(y) # Store the minimal y-position of the current layer # ======== Get colormap ======== blue = Color("blue") n_col_steps = 1000 colors = list(blue.range_to(Color("red"), n_col_steps)) # Colormap to be used for scaling the colors of # the neurons and the weights # ===== Plot neurons ===== for iLayer, n_pos in enumerate(neuron_positions): if iLayer == len(neuron_positions) - 1: output_layer = True input_layer = False t = theta[iLayer - 1] elif not iLayer: output_layer = False input_layer = True t = [] else: output_layer = False input_layer = False t = theta[iLayer - 1] if output_layer: neuron_value = [] for i in range(0, t.shape[0]): neuron_value.append(np.sum(t[i, :])) min_neuron_val = np.min(neuron_value) max_neuron_val = np.max(neuron_value) elif not input_layer: neuron_value = [] for i in range(0, t.shape[1]): neuron_value.append(np.sum(t[:, i])) min_neuron_val = np.min(neuron_value) max_neuron_val = np.max(neuron_value) else: neuron_value = [] min_neuron_val = None max_neuron_val = None for iNeuron, p in enumerate(n_pos): # Get synapse color if input_layer: # Input layer c = str(colors[0]) else: if iNeuron: col_idx = math.floor(((neuron_value[iNeuron - 1] - min_neuron_val) / (max_neuron_val - min_neuron_val)) * (n_col_steps - 1)) c = str(colors[col_idx]) else: c = str(colors[0]) draw_circle = plt.Circle((p[0], p[1]), radius=neuron_radius, color=c) axs.add_patch(draw_circle) # ===== Plot Connections ===== # extract min/max values, used if max&min weight values are not provided by user if not max_weight or not min_weight: max_weight = -np.inf min_weight = np.inf for t in theta: max_v = np.max(np.max(t)) min_v = np.min(np.min(t)) if max_weight < max_v: max_weight = max_v if min_weight > min_v: min_weight = min_v # Dynamically set the alpha values alpha = [] for iLayer, t in enumerate(theta): num_of_weights = t.shape[0] * t.shape[1] alpha.append((1 / num_of_weights) * 100) for iLayer, t in enumerate(theta): if iLayer == len(theta)-1: output_layer = True else: output_layer = False neurons_positions_prim_layer = neuron_positions[iLayer] neurons_positions_sec_layer = neuron_positions[iLayer+1] # Set alpha value a = alpha[iLayer] for i, p1 in enumerate(neurons_positions_prim_layer): for j, p2 in enumerate(neurons_positions_sec_layer): if j or output_layer: connection_weight = t[i, j-1] col_idx = math.floor(((connection_weight - max_weight) / (max_weight - min_weight)) * (n_col_steps - 1)) c = str(colors[col_idx]) plt.plot([p1[0], p2[0]], [p1[1], p2[1]], color=c, alpha=a) # ===== write theta sum text ===== y_pos = min(min_y_pos) + 2*neuron_distance x_pos = layer_distance/4 for t in theta: theta_sum = np.sum(np.sum(t)) theta_sum = np.floor(theta_sum*1000)/1000 s = 'weight sum: ' + str(theta_sum) plt.text(x_pos, y_pos, s) x_pos += layer_distance axs.set_xticks([]) # Delete x-ticks axs.set_yticks([]) # Delete y-ticks
f95a3729fcc7e2e5476081156a8f1d3a2378eb4d
Saneter/Education
/assignment_5_travis_jarratt.py
4,287
4.15625
4
""" author: Travis Jarratt CIS 1600 - Assignment 5 Saint Louis University """ def get_data(): fileObj = open("./exam-scores.csv") lines = fileObj.readlines() dict_scores = {} for line in lines[1:]: lst_items = line.strip().split(",") dict_scores[lst_items[0]] = (float(lst_items[1]), float(lst_items[2])) return dict_scores def print_menu(): print("\nEnter 1 to see all the scores") print("2 to see a particular student's score") print("3 to see the class average on a particular test") print("4 to see the students with the highest score") print("5 to display a list of students whose combined \n " "score on both the tests exceeds the average \n " "of the combined scores on the two tests") userchoice = int(input("and 0 to quit.")) return userchoice def display_all_data(dict_scores): print("Here are all the students' scores:") for stdname in dict_scores: print("%s: %f %f" % (stdname, dict_scores[stdname][0], dict_scores[stdname][1])) def display_specific_student_score(dict_scores): student_name = input("Provide the student's name whose scores you would like to retrieve: ") if not student_name in dict_scores: print("Student %s is not present in our records!" % student_name) else: print("Student %s's scores are: %s" % (student_name, str(dict_scores[student_name][0]) + " " + str(dict_scores[student_name][1]))) def display_average_score(dict_scores): test_no = int(input("Enter the number for the test: 1 for the first test and 2 for the second test: ")) if not test_no in (1, 2): print("Please enter a valid test number: either 1 or 2. You have entered: %d" % test_no) else: total = 0 for key in dict_scores: total += dict_scores[key][test_no - 1] print("The avg. score on test %d is %f" % (test_no, total / len(dict_scores))) def get_max_score(dict_scores, test_no): maxScore = 0 for key in dict_scores: if maxScore < dict_scores[key][test_no - 1]: maxScore = dict_scores[key][test_no - 1] return maxScore def display_max_scores_on_test(dict_scores): test_no = int(input("Enter the number for the test: 1 for the first test and 2 for the second test: ")) if not test_no in (1, 2): print("Please enter a valid test number: either 1 or 2. You have entered: %d" % test_no) else: maxScore = get_max_score(dict_scores, test_no) print("max score is " + str(maxScore)) for key in dict_scores: if dict_scores[key][test_no - 1] == maxScore: print("%s had a test score of %d" % (key, dict_scores[key][test_no - 1])) def student_combined_score_both_tests(dict_scores): temp_dict = {} for k, v in dict_scores.items(): temp_dict[k] = (v[0] + v[1]) return temp_dict def avg_score_both_tests(dict_scores): testTotal = 0 for v in dict_scores.values(): testTotal += ((v[0]) + (v[1])) return testTotal/len(dict_scores) def better_than_the_avg_on_both_tests(dict_scores): better_dict = {} temp = student_combined_score_both_tests(dict_scores) for k, v in temp.items(): if v > avg_score_both_tests(dict_scores): better_dict[k] = v print("The students who scored better\n" "than the average score both tests, {}, are: ".format(avg_score_both_tests(dict_scores))) for key, value in better_dict.items(): print("{} {}".format(key, value)) def run_ui(): dict_scores = get_data() while True: choice = print_menu() if choice == 0: print("Good bye!") quit() elif choice == 1: display_all_data(dict_scores) elif choice == 2: display_specific_student_score(dict_scores) elif choice == 3: display_average_score(dict_scores) elif choice == 4: display_max_scores_on_test(dict_scores) elif choice == 5: better_than_the_avg_on_both_tests(dict_scores) else: print("%d is an invalid choice" % choice) if __name__ == '__main__': run_ui()
cf4a38a0e60330d84e3de39e55d45cde94bf8486
Tusharsampang/LabProject2
/One.py
331
4.40625
4
''' 1.Write a program that takes numbers and print theirs sum.Every number is given on a separate line. ''' num1 = int(input("enter the first value: ")) num2 = int(input("enter the second value: ")) num3 = int(input("enter the third value: ")) sum = num1 + num2 + num3 print(sum) print(f"The sum of given three numbers is {sum}")
8e0400fa1f3956b2e70cb5084fab4abac5982b13
sevdaghalarova/Donguler
/List_comprehension.py
417
4.28125
4
# List Comrehension listeler uzerinde for dongusunu daha kisa yazmak icin kullanilir liste=[1,2,3,4,5] liste1=list() for i in liste: liste1.append(i) #print(liste1) # yukaridaki kodu list comprehension ile yazarsak liste1=[i for i in liste] liste1=[i*2 for i in liste] # her bir elemani 2-3 carpip liste1-e ekleyecek print(liste1) liste3=[(1,2),(2,3),(2,4)] liste4=[i for x in liste3 for i in x] print(liste4)
f2db23034447104787549f69b7c5c44f528fe044
saadz-khan/SpotDown
/SpotDown/spotipy_api/client.py
2,341
3.578125
4
from spotipy.oauth2 import SpotifyClientCredentials from spotipy import Spotify import json from sys import argv def spotify_authentication(client_id, client_secret, playlist_id): """ This part verifies the credentials for the spotify-api usage Args: client_id: client_secret: playlist_id: Playlist id in the link of the playlist Returns: All the data related to the playlists """ auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) sp = Spotify(auth_manager=auth_manager) return sp.playlist(playlist_id) def spotify_playlist_info(client_id, client_secret, playlist_id): """ This function retrives the track information inside of a playlist It inputs client_id and client_secret from spotify dashboard Along with a playlist_id from the link of the playlist. """ results = spotify_authentication(client_id, client_secret, playlist_id) track_list = [] #print("Song - Artist - Album\n") for item in results['tracks']['items']: track_list.append(item['track']['name'] + ' - ' + item['track']['artists'][0]['name']) # For album name in the search query uncomment this #+ ' - ' + #item['track']['album']['name']) #print(track_list) return track_list def output_json(client_id, client_secret, playlist_id): """ To output a json file from it """ results = spotify_authentication(client_id, client_secret, playlist_id) # Creating a data structure for json format. result_dict = { 'tracks': { 'items': [], 'limit': 100, 'next': None, 'offset': 0, 'previous': None, 'total': 16 }, 'type': 'playlist', 'uri': playlist_id } for item in results['tracks']['items']: track_dict = { 'track': { 'album': { 'name': item['track']['album']['name'], }, 'artists': [{ 'name': item['track']['artists'][0]['name'], }], 'name': item['track']['name'], } } result_dict['tracks']['items'].append(track_dict) # Append the track dict structure to your results dict structure out_file = open('track.json','w') json.dump(result_dict, out_file, indent = 4) # Sample Script """ c_id = str(argv[1]) c_secret = str(argv[2]) p_id = str(argv[3]) p_id = p_id[34:] spotify_playlist_info(c_id, c_secret, p_id) """
1ac326f8a1aadb038ce4ce4502afa9a9de07640b
bhaavanmerchant/challenge-problems
/skycompany/Tree.py
826
3.765625
4
class Tree: root = { 'value': None, 'children': [] } def __init__(self, val): self.root = self._create_node(val) return self.root def _create_node(self, val): return { 'value': val, 'children': [] } def create_child(self, val): new_node = self._create_node(val) self.root.append(new_node) return new_node def print_tree(node): print(node['value']) if len(node['children'] == 0): return None print('\/\/') for child_node in node['children']: self.print_tree(child_node) def traverse_bfs(node): if __name__ == '__main__': root = Tree(3) root.create_child(2) Tree.create_child(root, 4) Tree.print_tree(root)
5c30c871d1372ec6d61ff1b195ed2877972bdc42
hellokena/goorm
/1단계/홀짝 판별.py
61
3.921875
4
n = int(input()) if n%2==0: print('even') else: print('odd')
f0e6b2ace850a92b0771dc2844ca6a2b1bfdcc8b
aliKatlabi/Python_tut
/tutorial/DataStructure.py
937
3.546875
4
vec = [-4, -2, 0, 2, 4] # create a new list with the values doubled [x*2 for x in vec] #[-8, -4, 0, 4, 8] # filter the list to exclude negative numbers [x for x in vec if x >= 0] #[0, 2, 4] # apply a function to all the elements [abs(x) for x in vec] #[4, 2, 0, 2, 4] # call a method on each element freshfruit = [' banana', ' loganberry ', 'passion fruit'] [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] # create a list of 2-tuples like (number, square) [(x, x**2) for x in range(6)] #[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] # the tuple must be parenthesized, otherwise an error is raised #[x, x**2 for x in range(6)] # File "<stdin>", line 1, in <module> # [x, x**2 for x in range(6)] # ^ #SyntaxError: invalid syntax # flatten a list using a listcomp with two 'for' vec = [[1,2,3], [4,5,6], [7,8,9]] [num for elem in vec for num in elem] #[1, 2, 3, 4, 5, 6, 7, 8, 9]
b9d2cd65a38cf0cbc57508d5c71d8553973d77e0
joaovbs96/Logistic-Regression-Neural-Networks-MC886-2018s2
/nnOneHiddenLayer.py
6,437
3.765625
4
# coding: utf-8 # MC886/MO444 - 2018s2 - Assignment 02 - Neural Network with One Hidden Layer # Tamara Campos - RA 157324 # João Vítor B. Silva - RA 155951 import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import itertools from sklearn.preprocessing import MinMaxScaler from sklearn.decomposition import PCA from sklearn.metrics import f1_score from sklearn.metrics import confusion_matrix # source: http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout() # ========================================= # relu derivative function def relu_derivative(z): def do_relu_deriv(x): if x > 0: return 1 else: return 0 relufunc = np.vectorize(do_relu_deriv) return relufunc(z) # relu function def relu(z): def do_relu(x): return max(0, x) relufunc = np.vectorize(do_relu) return relufunc(z) # Stable softmax function def softmax(z): z -= np.max(z) sm = (np.exp(z).T / np.sum(np.exp(z),axis=1)).T return sm # Function to transform target data into one hot encode def oneHotEncode(y, k): return np.eye(k)[y] # calculate loss using cross entropy function def loss(h, y): m = len(y) cost = (-1 / m) * np.sum(np.sum(y * np.log(h + 0.0001) + (1. - y) * np.log((1 - h) + 0.0001), axis=1)) return cost # Train the neural network doing feed forward and backpropagation def NeuralNetwork(x, y, it, alpha): classes = len(y[0]) # number of classes _, n = x.shape # n: number of features secondLayerSize = 64 # number of neurons in the second layer # step by step: check slide 68 # step 1 - random init in [0, 1) weights1 = np.random.rand(n, secondLayerSize) weights2 = np.random.rand(secondLayerSize, classes) J = [] for i in range(it): # step 2 - feed forward - slide 41 # First activation function # z1 = f(W1 * x + b1) z1 = np.dot(x, weights1) a1 = relu(z1) # Second activation function(softmax) # z2 = softmax(W2 * z1 + b2) z2 = np.dot(a1, weights2) a2 = softmax(z2) # step 3 - calculate output error J.append(loss(a2, y)) # step 4 - calculate derivative of error # step 5 - backpropagate # step 6 - update the weights with the derivative cost function dz2 = (y - a2) # the last layer don't use activation function derivative dw2 = a1.T.dot(dz2) dz1 = dz2.dot(weights2.T) * relu_derivative(a1) dw1 = x.T.dot(dz1) weights2 += dw2 * alpha weights1 += dw1 * alpha return [weights1, weights2], J # MAIN # execução: main.py [train_data] # dataset: https://www.dropbox.com/s/qawunrav8ri0sp4/fashion-mnist-dataset.zip # disable SettingWithCopyWarning warnings pd.options.mode.chained_assignment = None # default='warn' # Read main database trainName = sys.argv[1] data = pd.read_csv(trainName) # read test database filename = sys.argv[2] testData = pd.read_csv(filename) # separate target/classes from set Y = data.drop(data.columns.values[1:], axis='columns') X = data.drop('label', axis='columns') # separate target/classes from test set testY = testData.drop(testData.columns.values[1:], axis='columns') testX = testData.drop('label', axis='columns') # split dataset into train and validation trainX, validX = X.iloc[12000:], X.iloc[:12000] trainY, validY = Y.iloc[12000:], Y.iloc[:12000] # Dimensionality reduction pca = PCA(.98) trainX = pca.fit_transform(trainX) validX = pca.transform(validX) testX = pca.transform(testX) # normalize train, validation ans test with the max value in the matrix - monocromatic images trainX /= 255.0 validX /= 255.0 testX /= 255.0 # target OndeHotEncode and reduction from 3d to 2d matrix y = np.squeeze(oneHotEncode(trainY, len(np.unique(trainY)))) # train neural network it = 1000 # tested alphas: 0.000001, 0.0000001, 0.00000001 - Better: 0.000001 alphas = [0.000001] for alpha in alphas: weights, J = NeuralNetwork(trainX, y, it, alpha) # plot graph for GD with regularization plt.plot(J) plt.ylabel('Função de custo J') plt.xlabel('Número de iterações') plt.title('Rede Neural com uma camada escondida') plt.show() # ============== VALIDATION z1Valid = relu(np.dot(validX, weights[0])) resultsValid = softmax(np.dot(z1Valid, weights[1])) yPredValid = [] for r in resultsValid: yPredValid.append(np.argmax(r)) # Accuracy print("VALIDAÇÃO ----> REDE NEURAL COM 1 CAMADA ESCONDIDA - ALPHA", str(alpha), " - ", str(it), " ITERAÇÕES") print("F1 Score:" + str(f1_score(validY, yPredValid, average='micro'))) # ============= TEST # calculte output value z1 = relu(np.dot(testX, weights[0])) results = softmax(np.dot(z1, weights[1])) yPred = [] for r in results: yPred.append(np.argmax(r)) # Accuracy print("TESTE ----> REDE NEURAL COM 1 CAMADA ESCONDIDA - ALPHA", str(alpha), " - ", str(it), " ITERAÇÕES") print("F1 Score:" + str(f1_score(testY, yPred, average='micro'))) # confusion matrix cm = confusion_matrix(testY, yPred) plt.figure() plot_confusion_matrix(cm, classes=[str(i) for i in range(10)], normalize=False, title='Confusion Matrix') plt.show()
feccaf38a397e46c4d1c0d0ffa3de9501d278d11
edD9m/codingground
/New Project/main.py
2,412
4.28125
4
print "Hi, my name is Python! I'm a programming language that's intelligent but simple! Enjoy your stay!" print "Soo, please answer my questions." myname=raw_input("What's your name? >>> ") print "Nice to meet you, " + " " + myname if myname == "myname" : print "Oh, by the way, don't enter the name of the variable, thanks." if myname == "name" : print "Yes, I know it's a name, but what IS your name?" print "Good! Let's move on forward! How about I calculate a sum of two variables?" calc=raw_input("So, shall I? You can answer either yes or no in downcase so my script will work properly! ") if calc == "yes." : a=20 b=30 print a+b,"is the answer." else : print "Well, I can't complain, so, shall we go on? " shallwe=raw_input("So, shall we go on? Answer yes or no in downcase. ") if shallwe == "yes" : print "Well, let's go on! Now, let me calculate a complex mathematical equation!" else : print "I can't complain, but shall we go forward?" shallwe2=raw_input("Shall we? ") if shallwe2 == "yes" : print "Haha, you are interested already!" else : print "Well, well, well." v=30 c=20 numbers=v+c print ("My calculations say: %i meters." % numbers) print "Well, I think you are enjoying this! Shall we go on?" go_on=raw_input("Shall we?") if go_on == "yes" : print "So, let's go on!" else : print "Well, that's fine by me!" shallweend=raw_input("So, shall we end your first course or shall we continue? ") if shallweend == "yes" : print "Goodbye!" else : print "Well, if you want to continue the ride, let's go on!" print "Now, let me show ya simple lists." list = ["cats", "bong", "hey!", "hockey"] print list del list[2] print list print "This is the end of course 1, goodbye!" print "INTERACTIVE PYTHON" print "by edD." print "------------------------------------" print "Well, shall we start course 2?" shallwe3=raw_input("Shall we or no? ") if shallwe3 == "yes" : print "Alright!" else : print "Well, that's fine." print "Course 2 will be exclusive to some more fun script." print "So, let me show you how to print out all the letters in Python." for letter in "Python": print "Current letter: ", letter print "Here is an another example." vegetables = ['tomato', 'potato', 'carrot'] for vegetable in vegetables: print "Current vegetable: ", vegetable print "Well, this is the short end of the first part of the guide."
7436a98a489b0a0f39242ad99b0b83b170171145
Rapid1898-code/codesignal
/arcade/level54.py
367
3.734375
4
def sumUpNumbers(inputString): listString = list(inputString) newString = "" countSum = 0 for char in listString: if char.isdigit(): newString += char else: newString += " " newList = newString.split(" ") for elem in newList: if elem != "": countSum += int(elem) return countSum
38231e47076d65f330d68dd5a4f47ef8843cd8de
kat0h/timetable_bot
/get_timetable.py
1,128
3.59375
4
import csv import sys def get_timetable(filepath: str): # 時間割の読み取り with open(filepath) as f: reader = csv.reader(f) tt = [row for row in reader] timetable = {} for i in tt: timetable[i[0]] = i[1:7] return timetable def get_schedule(filepath: str): # 時間割の読み取り with open(filepath) as f: reader = csv.reader(f) sd = [row for row in reader] schedule = {} for i in sd: schedule[i[0]] = i[1] return schedule if __name__ == "__main__": time_table = get_timetable(sys.argv[1]) schedule = get_schedule(sys.argv[2]) date_today = sys.argv[3] today = schedule[date_today] print("今日{}の時間割は・・・\n".format(date_today)) if today == "特": print("今日は特編授業です") elif today == "休": print("🎉🎉🎉今日は休日です🎉🎉🎉") else: today_time_table = time_table[today] print("今日は{}です".format(today)) for i in range(1, 7): print("{}時限 | {} ".format(i, today_time_table[i-1]))
5e0d0f760ac4bda396a4bb8ba9f408d5af7598e0
jigonzalez124/morseCode
/morseCode.py
1,195
3.984375
4
# Name: Jesus Ivan Gonzalez # Date: July 20th 2015 # Description: Simple morse code program. Note: / indicates whitespace def morse(code): morseCode = { '.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e', '..-.': 'f', '--.': 'g', '....': 'h', '..': 'i', '.---': 'j', '-.-': 'k', '.-..': 'l', '--': 'm', '-.': 'n', '---': 'o', '.--.': 'p', '--.-': 'q', '.-.': 'r', '...': 's', '-': 't', '..-': 'u', '...-': 'v', '.--': 'w', '-..-': 'x', '-.--': 'y', '--..': 'z' } return morseCode[code]; def main(): fileName = input("Enter the morse code file name to decode: ") fhandle = open(fileName) for line in fhandle: #read each line of the file code = line.split() #split line to letters. '/' character indicates word space final_msg = [] for letter in code: if letter == "/": #if letter is /, then replace with whitespace final_msg.append(" ") else: final_msg.append(morse(letter)) #call morse method print("".join(final_msg)) if __name__ == '__main__': main()
7900a6d984ef3a63b380fd528a411acbf43ec52d
Ragav-Subramanian/My-LeetCode-Submissions
/923. 3Sum With Multiplicity Python Solution.py
323
3.5
4
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: twosums={} ans=0 for i in range(len(arr)): ans+=twosums.get(target-arr[i],0) for j in range(i): twosums[arr[i]+arr[j]]=twosums.get(arr[i]+arr[j],0)+1 return ans%(10**9+7)
663e0b6ffc2069637d90ca4cba24cc7b676c8930
GiantSweetroll/Program-Design-Methods-and-ITP
/Exercises/Lists and Dictionaries/Student.py
1,536
3.875
4
eren = { "name": "Eren", "homework": [90.0,97.0,75.0,92.0], "quizzes": [88.0,40.0,94.0], "tests": [75.0,90.0] } mikasa = { "name": "Mikasa", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } armin = { "name": "Armin", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } students = [eren, mikasa, armin] for student in students: print("Name:", student["name"]) print("Homework:", student["homework"]) print("Quizzes:", student["quizzes"]) print("Tests:", student["tests"]) def average(numbers:[float]) -> float: total = sum(numbers) total = float(total) return total/len(numbers) def get_average(student:{})-> float: homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"]) homework *= 0.1 quizzes *= 0.3 tests *= 0.6 return homework+quizzes+tests def get_letter_grade(score:float) -> str: if (score >= 90): return "A" elif (score >= 80): return "B" elif (score >= 70): return "C" elif (score >= 60): return "D" else: return "F" print(get_letter_grade(get_average(lloyd))) #"with lloyd", who is lloyd def get_class_average(students:[{}]): results = [] for student in students: results.append(get_average(student)) return average(results) print(get_class_average(students)) print(get_letter_grade(get_class_average(students)))
efee6903cd41bc93ee9afee9a354a26182eee9d9
chaofan-zheng/tedu-python-demo
/month01/all_code/day17/demo09.py
1,938
3.546875
4
""" 需求: 定义函数,在员工列表中查找最富的员工 定义函数,在员工列表中查找xxx的员工 步骤: 1. 根据需求,写出函数。 2. 因为主体逻辑相同,核心算法不同. 所以使用函数式编程思想(分、隔、做) 创建通用函数get_max(定义到单独模块中) 3. 在当前模块中调用(使用lambda) """ from common.iterable_tools import IterableHelper class Employee: def __init__(self, eid, did, name, money): self.eid = eid # 员工编号 self.did = did # 部门编号 self.name = name self.money = money # 员工列表 list_employees = [ Employee(1001, 9002, "师父", 60000), Employee(1002, 9001, "孙悟空", 50000), Employee(1003, 9002, "猪八戒", 20000), Employee(1004, 9001, "沙僧", 30000), Employee(1005, 9001, "小白龙", 15000), ] def get_max01(): max_value = list_employees[0] for i in range(1, len(list_employees)): if max_value.money < list_employees[i].money: max_value = list_employees[i] return max_value def get_max02(): max_value = list_employees[0] for i in range(1, len(list_employees)): if max_value.eid < list_employees[i].eid: max_value = list_employees[i] return max_value def handle01(emp): return emp.money def handle02(emp): return emp.eid def get_max(func): max_value = list_employees[0] for i in range(1, len(list_employees)): # if max_value.eid < list_employees[i].eid: # if handle02(max_value) < handle02(list_employees[i]): # if handle01(max_value) < handle01(list_employees[i]): if func(max_value) < func(list_employees[i]): max_value = list_employees[i] return max_value emp = IterableHelper.get_max(list_employees, lambda item: item.money) print(emp.__dict__)
c837c5f673c0a18aa7b17b01bfec37a84e397a23
Khananashvili/WEB
/LR2/Code_2.2.py
145
3.65625
4
s=str(input("Введите строку: ")) k=s.split(' ') for i in range (len(k)): if (k[i][len(k[i])-1:])=='r': print(k[i])
39567f773e1395b4bf94da9fe4505cff5621f350
df413/leetcode
/maximum_subarray/solution.py
780
4
4
class Solution(object): """ Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. """ def find_maximum_subarray(self, nums): max_sum = nums[0] current_sum = nums[0] for i in range(1, len(nums)): if current_sum < 0: current_sum = 0 current_sum += nums[i] if max_sum < current_sum: max_sum = current_sum return max_sum if __name__ == "__main__": sol = Solution() print(sol.find_maximum_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) print(sol.find_maximum_subarray([-2, 1]))
33bfd882d31d1b3114a2a0cb23557b020cfdce0d
DylanDu123/leetcode
/142.环形链表-ii.py
873
3.5625
4
# # @lc app=leetcode.cn id=142 lang=python3 # # [142] 环形链表 II # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def fetchPoint(self, head: ListNode): fast, slow = head, head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if fast == slow: return fast return None def detectCycle(self, head: ListNode) -> ListNode: if not head or not head.next: return None node = self.fetchPoint(head) if not node: return None curr = head while curr != node: curr = curr.next node = node.next pass return curr # @lc code=end
2e44f6334967d048fd634fd71bfbfaacb97a0ef5
kavithacm/MITx-6.00.1x-
/Week 4- Good Programming Practices/7. Testing and Debugging/Exercise- Integer Division
1,080
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 22 14:27:13 2018 @author: Kavitha """ ''' Exercise: integer division 5.0/5.0 points (graded) ESTIMATED TIME TO COMPLETE: 4 minutes Consider the following function definition: def integerDivision(x, a): """ x: a non-negative integer argument a: a positive integer argument returns: integer, the integer division of x divided by a. """ while x >= a: count += 1 x = x - a return count When we call print(integerDivision(5, 3)) we get the following error message: File "temp.py", line 9, in integerDivision count += 1 UnboundLocalError: local variable 'count' referenced before assignment Your task is to modify the code for integerDivision so that this error does not occur. ''' def integerDivision(x, a): """ x: a non-negative integer argument a: a positive integer argument returns: integer, the integer division of x divided by a. """ count=0 while x >= a: count += 1 x = x - a return count ##Correct
2926b14261b2c450b0d29d34f802ea63b40e592c
edadasko/coursera_algorithms
/graphs/dijkstra.py
917
3.53125
4
from queue import PriorityQueue INF = float('inf') def distance(adj, cost, s, t): q = PriorityQueue() n = len(adj) min_costs = [INF] * n for i in range(n - 1): q.put((INF, i)) q.put((0, s)) min_costs[s] = 0 for _ in range(len(adj) - 1): min_node = q.get() from_cost, from_node = min_node[0], min_node[1] for to_node in adj[from_node]: to_cost = from_cost + cost[from_node, to_node] if min_costs[to_node] > to_cost: min_costs[to_node] = to_cost q.put((to_cost, to_node)) return min_costs[t] if min_costs[t] != INF else -1 n, m = map(int, input().split()) adj = [[] for _ in range(n)] cost = {} for i in range(m): a, b, c = map(int, input().split()) adj[a - 1].append(b - 1) cost[a - 1, b - 1] = c s, t = map(int, input().split()) s, t = s - 1, t - 1 print(distance(adj, cost, s, t))
1e904e2bc98bb6a16844b1c9146de7f6d3af21ff
Ivanochko/lab-works-python
/Topic 07. Strings, Bytes, Bytearray/lab7_11.py
203
3.71875
4
arr = [(i, len(i)) for i in input('Введіть речення на сорт.: ').split(' ')] arr = sorted(arr, key=lambda x: x[1], reverse=True) print() for x, i in arr: print(x, end=' ') print()
114be0800d32d9221ec5c4c290612e0828b72c7e
haekyu/python_tutoring_ys
/1029/hw_sol/mk_csv.py
608
4.03125
4
""" 2. 파일 출력 연습 어떠한 리스트를 csv (comma-separated values) 포맷으로 텍스트파일에 저장해보세요. 예) [[1, 2, 3, 5], [3, 5, 2, 1], [5, 3, 1, 5]] 라는 리스트가 주어져 있으면 1,2,3,5 3,5,2,1 5,3,1,5 로 텍스트파일(파일 이름 맘대로)에 저장해 보세요. """ def save_mat_csv(filename, mat): f = open(filename, 'w') for rows in mat: for th, element in enumerate(rows): f.write("%s" % element) if th < len(rows) - 1: f.write(",") f.write("\n") mat = [[1, 2, 3, 5], [3, 5, 2, 1], [5, 3, 1, 5]] save_mat_csv('./result_csv.txt', mat)
dcc50569d07ca76d99b486295fa0f9e15ed6d4c6
paige0701/rockpaperscissors
/main.py
1,570
3.953125
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. from enum import IntEnum class Action(IntEnum): Rock = 0 Paper = 1 Scissors = 2 def get_user_selection(): choices = ', '.join([f"{action.name}[{action.value}]" for action in Action]) user_input = int(input(f"Enter a choice ({choices}): ")) action = Action(user_input) return action def get_computer_selection(): import random random_int = random.randint(0, len(Action)-1) action = Action(random_int) return action def determine_winner(user, computer): answer = { Action.Paper: [Action.Rock], Action.Rock: [Action.Scissors], Action.Scissors: [Action.Paper] } defeat = answer[user] if user == computer: print(f"YOU: {user.name} Vs COMPUTER: {computer.name} = It's a tie") elif computer in defeat: print(f"YOU: [{user.name}] Vs COMPUTER: {computer.name} = You win!") else: print(f"YOU: {user.name} Vs COMPUTER: [{computer.name}] = You lose") def play_game(): while True: user_selection = get_user_selection() computer_selection = get_computer_selection() determine_winner(user_selection, computer_selection) user_input = input("Play again? Y/N : ") if user_input.upper() == 'N': break # Press the green button in the gutter to run the script. if __name__ == '__main__': play_game()
08b9b45752de1a0cf21337ff86d3f92ec0400b9d
spencerstock/Sprint-Challenge--Computer-Architecture
/ls8/cpu.py
4,432
3.5625
4
"""CPU functionality.""" import sys class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.ram = [0] * 256 self.registers = [0] * 8 self.registers[7] = 0xF4 self.fl = 0b00000000 self.pc = 0 def load(self, path): """Load a program into memory.""" address = 0 # Loads program from ls8.py program = [] try: with open(path) as f: for line in f: comment_split = line.split("#") num = comment_split[0].strip() if num != "": program.append(int(num, 2)) except FileNotFoundError: print(f"{path} not found") sys.exit(2) for instruction in program: self.ram[address] = instruction address += 1 def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == "ADD": self.registers[reg_a] += self.registers[reg_b] elif op == "SUB": self.registers[reg_a] -= self.registers[reg_b] else: raise Exception("Unsupported ALU operation") def ram_read(self, position): return self.ram[position] def ram_write(self, position, value): self.ram[position] = value def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f"TRACE: %02X | %02X %02X %02X |" % ( self.pc, #self.fl, #self.ie, self.ram_read(self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2) ), end='') for i in range(8): print(" %02X" % self.registers[i], end='') print() def run(self): """Run the CPU.""" running = True while running: command = self.ram_read(self.pc) if command == 0b00000001: #HALT running = False self.pc += 1 print("Halted") sys.exit(1) elif command == 0b10000010: #LDI reg = self.ram_read(self.pc + 1) num = self.ram_read(self.pc + 2) self.registers[reg] = num self.pc += 3 elif command == 0b01000111: #PRN reg = self.ram_read(self.pc + 1) num = self.registers[reg] print(num) self.pc += 2 elif command == 0b10100010: #MUL reg_a = self.registers[self.ram_read(self.pc + 1)] reg_b = self.registers[self.ram_read(self.pc + 2)] self.registers[self.ram_read(self.pc + 1)] = reg_a * reg_b self.pc += 3 elif command == 0b01010100: #JMP reg = self.ram_read(self.pc + 1) self.pc = self.registers[reg] elif command == 0b10100111: #CMP # clear flags from last time cmp ran self.fl = 0b00000000 # get values from ram reg_1 = self.ram_read(self.pc + 1) reg_2 = self.ram_read(self.pc + 2) val_1 = self.registers[reg_1] val_2 = self.registers[reg_2] # make comparisons if val_1 == val_2: self.fl = 0b00000001 #Equal elif val_1 < val_2: self.fl = 0b00000100 #Greater Than elif val_1 > val_2: self.fl = 0b00000010 #Less Than self.pc += 3 elif command == 0b01010101: #JEQ if self.fl == 0b00000001: reg = self.ram_read(self.pc + 1) self.pc = self.registers[reg] else: self.pc += 2 elif command == 0b01010110: #JNE if self.fl == 0b00000100 or self.fl == 0b00000010: reg = self.ram_read(self.pc + 1) self.pc = self.registers[reg] else: self.pc += 2 else: print(f"Unkown command {command}") self.pc += 1 print(self.pc)
426777904ce7f66b904c4bd97386bb34ee8aebb7
anrom7/Array
/multiset/multiset.py
1,827
3.734375
4
from multiset.array_list import MyArray class Multiset: def __init__(self): """ Produces a newly constructed empty Multiset. """ self.data = MyArray(100) self.firstempty = 0 def empty(self): """ Checks emptiness of Multiset. :return: True if Multiset is empty and False otherwise. """ for index in range(self.firstempty): if self.data[index] != None: return False return True def __contains__(self, value): """ Checks existence of value in the Multiset. :param value: the value to be check. :return: True if Multiset is in the Multiset and False otherwise. """ for index in range(self.firstempty): if self.data[index] == value: return True return False def add(self, value): """ Adds the value to multiset. :param value: the value to be added.. """ self.data[self.firstempty] = value self.firstempty = self.firstempty + 1 def delete(self, value): """ Deletes value from multiset. :param value: value firs occurrence of which should be deleted. """ position = -1 current = 0 while position == -1 and current < self.firstempty: if self.data[current] == value: position = current else: current = current + 1 if current < self.firstempty: for updated in range(position, self.firstempty): self.data[updated] = self.data[updated + 1] self.data[self.firstempty] = None self.firstempty = self.firstempty - 1
4ed7d7ac539651da3b4be4da47f0f0cfb3e572a3
dlaevskiy/arhirepo
/fluent_python/2_sequence_array/1_listcomp_and_genexp.py
576
3.578125
4
# list comprehensive import array colors = ['black', 'white', ] sizes = ['S', 'M', 'L'] tshirts = [(color, size) for color in colors for size in sizes] print(tshirts) # generators symbols = '@#$%^7' gen = tuple(ord(symbol) for symbol in symbols) print(gen) ar = array.array('I', (ord(symbol) for symbol in symbols)) print(ar) # tuples year, name = (1989, 'Dzmitry') a, b, *rest = range(5) print(a, b, *rest) s = 'sdjhjkdhfodjsjfdjflkjdsouwijfhfdh' def split_len(seq, length): return [seq[i:i+length] for i in range(0, len(seq), length)] print(split_len(s, 10))
0a1385c2e0ad0c6be68f336ba9ef6588b3e4bd8f
koskot77/leetcode
/1448treePath.py
924
3.640625
4
# https://leetcode.com/problems/count-good-nodes-in-binary-tree/submissions/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def helper(self, node, maximum): n_good = 0 # error #1: think what you are going to return upfront if node.val >= maximum: n_good = 1 maximum = node.val # error #2 don't make it more complicated with checking for leaf if node.left != None: n_good += self.helper(node.left,maximum) if node.right != None: n_good += self.helper(node.right,maximum) return n_good def goodNodes(self, root): """ :type root: TreeNode :rtype: int """ return self.helper(root,-1000000)
a5ef8d78f80fa0c4c07fe039408c5b1a56baf800
Zoogster/python-class
/Project 1/admin.py
3,802
4.25
4
"""Lets an admin look at the roster and change max class size show_roster -- Displays roster of a course. change_max_size -- Allows admin to change max class size """ def show_roster(r_list): """Displays the roster for a chosen course Checks to make sure the course entered is valid. If valid desplays student IDs enrolled in that course sorted """ choose_course = input*('Choose a course: ') choose_course = choose_course.upper() if choose_course != 'CSC121' or choose_course != 'CSC122' or choose_course != 'CSC221': print('Error: Not a valid course') return if choose_course == 'CSC121': print('Students in CSC121: ', r_list[0].sort()) return elif choose_course == 'CSC122': print('Students in CSC122: ', r_list[1].sort()) return else: print('Students in CSC221: ', r_list[2].sort()) return def change_max_size(r_list, m_list): """Allows an admin to change the class size of any course Asks what course they wish toe change the max size of and checks to make sure it is a valid course Asks what the new max size should be and makes sure it isn't lower than the current amout enrolled in it """ while True: course_to_change = input( 'What course do you wish to change the max class size of? ') course_to_change = course_to_change.upper() if course_to_change == 'CSC121' or course_to_change == 'CSC122' or course_to_change == "CSC221": break else: print('Error: Invalid course') if course_to_change == 'CSC121': print( f'The number of students currenty enrolled in CSC121 is {len(r_list[0])} and the current max class size is {m_list[0]}.') new_max_size = int( input('What do you want to change the max class size of CSC121 to? ')) while True: if new_max_size < len(r_list[0]): print( 'Error: New max class size can not be smaller than the number of current students enrolled in the course.') new_max_size = int(input( f'Please enter a new max class size that is greater or equal to {len(r_list[0])}. ')) else: break m_list[0] = new_max_size return elif course_to_change == 'CSC122': print( f'The number of students currenty enrolled in CSC122 is {len([1])} and the current max class size is {m_list[1]}.') new_max_size = int( input('What do you want to change the max class size of CSC122 to? ')) while True: if new_max_size < len(r_list[1]): print( 'Error: New max class size can not be smaller than the number of current students enrolled in the course.') new_max_size = int(input( f'Please enter a new max class size that is greater or equal to {len(r_list[1])}.')) else: break m_list[1] = new_max_size return else: print( f'The number of students currenty enrolled in CSC221 is {len(r_list[2])} and the current max class size is {m_list[2]}.') new_max_size = int( input('What do you want to change the max class size of CSC221 to? ')) while True: if new_max_size < len(r_list[2]): print( 'Error: New max class size can not be smaller than the number of current students enrolled in the course.') new_max_size = int(input( f'Please enter a new max class size that is greater or equal to {len(r_list[2])}.')) else: break m_list[2] = new_max_size return
1c312af821a9253a41a9a87ff566b41daebba346
kunweiTAN/techgym_ai
/0LTh.py
652
3.765625
4
#AI-TECHGYM-3-2-Q-2 #回帰問題と分類問題 #インポート import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model #データを作成 #0〜1までの乱数を100個つくる x = np.random.rand(100, 1) #値の範囲を-2~2に調整 x = x * 4 - 2 #yの値をつくる #標準正規分布(平均0,標準偏差1)の乱数を加える y += np.random.randn(100, 1) #モデル model = linear_model.LinearRegression() #係数、切片を表示 print('係数', model.coef_) print('切片', model.intercept_) #決定係数 #グラフ表示 plt.scatter(x, y, marker='o') plt.show()
2f2e90c195fdd811873c904f23aab19308ee83f4
ESE205/fl_19_mod_9
/mod9_func.py
341
3.640625
4
def movingAvg(array_list, numvals_for_average, size_of_array, position): sumvals = 0 for i in range(numvals_for_average): if (position - i >= 0): sumvals = sumvals + array_list[position - i] else: sumvals = sumvals + array_list[size_of_array + (position - i)] return sumvals/numvals_for_average
30c73b09c79b659ce6cae69377e313c37ea69809
jarroba/Curso-Python
/Casos Prácticos/4.17-bucle_condicional_salida.py
309
3.921875
4
# 1 continua = True # 2 uno = False dos = False tres = False # 3 while continua: # 4 print("uno: {}, dos: {}, tres: {}".format(uno, dos, tres)) # 5 if not uno: uno = True elif not dos: dos = True elif not tres: tres = True else: continua = False
f9e37d84a0b00ab191270c8a582c5d8449866edf
letoshelby/codewars-tasks
/6 kyu/IQ test.py
683
4.3125
4
# Description: # Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of # the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. # Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, # and return a position of this number. # ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0) def iq_test(numbers): e = [int(i) % 2 for i in numbers.split()] return e.index(True) + 1 if e.count(1) == 1 else e.index(False) + 1
8be15612b4c3fcd38b642474c9f0ad165a0ea386
gdh756462786/Leetcode_by_python
/Array/Find All Duplicates in an Array.py
706
4.03125
4
# coding: utf-8 ''' Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,8,2,3,1] Output: [2,3] ''' class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ ans = [] for n in nums: if nums[abs(n) - 1] < 0: ans.append(abs(n)) else: nums[abs(n) - 1] *= -1 return ans solution = Solution() print solution.findDuplicates([5,4,6,7,9,3,10,9,5,6])
d63792db1c43815b7dbc63ad65e2ae789a6bd4bc
tp00012x/Hacker-Rank
/Python/Strings/Text Wrap.py
337
3.625
4
# Textwrap # # The textwrap module provides two convenient functions: wrap() and fill(). # # textwrap.wrap() # The wrap() function wraps a single paragraph in text (a string) so that every line is width characters long at most. # It returns a list of output lines. def wrap(string, max_width): return textwrap.fill(string,max_width)
0957e8a5213196a6c5d35606fb3603890ba717e7
bwhitaker10/Python
/python/fundamentals/funcint1.py
754
3.921875
4
import random def randInt(min='', max=''): a = random.random() * ((randInt(max='')) - (randInt(min='')) + (randInt(min='')) b = random.random() * (100 - (randInt(min='')) + (randInt(min='')) c = random.random() * (randInt(max='')) d = random.random() if randInt(min='', max=''): return a elif randInt(min=''): return b elif randInt(max=''): return c elif randInt(): return d #print(randInt()) # should print a random integer between 0 to 100 #print(randInt(max=50)) # should print a random integer between 0 to 50 #print(randInt(min=50)) # should print a random integer between 50 to 100 #print(randInt(min=50, max=500)) # should print a random integer between 50 and 500
7428bdd3d23700f96945cac313223efe189182f1
SEU-CodingTogether/Daily-Python
/Level-00-Elementary/solutions/s19.py
665
4.0625
4
def most_frequent(data: list) -> str: """ determines the most frequently occurring string in the sequence. """ # your code here d = dict(zip(list(set(data)), map(data.count, list(set(data))))) return sorted(d, key=lambda x:d[x])[-1] if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing print('Example:') print(most_frequent([ 'a', 'b', 'c', 'a', 'b', 'a' ])) assert most_frequent([ 'a', 'b', 'c', 'a', 'b', 'a' ]) == 'a' assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi' print('Done')
651b022796c0c1de8fb27df38ae5b7adfac1930c
maypel/docstring_exercices
/jeux_aleatoire.py
1,119
3.78125
4
from random import randint nombre = randint(1, 101) # sélection du chiffre # intro et paramètres du jeux print("***Le jeu du nombre mystère***") essais = 5 print(f"Il te reste {essais} essais") # boucle du jeux while True: num = input('Devine le nombre :') # choix du joueur if num.isdigit() == True: # on vérifie que l'entrée du joueur soit bien un chiffre if int(num) == nombre: # victoire print(f"Bravo vous avez gagné en {6 - essais}\n" "Fin du jeux") break elif int(num) > nombre: # autres cas print(f"Le nombre mystère est plus petit que {num}") else: print(f"Le nombre mystère est plus grand que {num}") essais -= 1 # on enlève une chance print(f"Il te reste {essais}") if essais == 0: # quand le nombre de chance est épuisées print(f"Dommage ! Le nombre mystère était {nombre}\n" "Fin du jeux") break else: print("Veuillez entrer un nombre valide") # quand l'entrée du joueur n'est pas un chiffre
10790df43ef3b4b0df78aed9fbb6e4ae787fcf20
clickpn/final_proj
/UpdatedProject1207/general_functions.py
1,178
3.546875
4
import pickle '''to merge with other teammates''' def get_dictionary(filename): '''The function takes a dictionray.p file as input and returns a dictionary.''' dictionary = pickle.load(open(filename, 'rb')) return dictionary def data_extract(data, startyear, startmonth, endyear, endmonth): data_by_year_start = data.loc[data['startyear'] == startyear] data_by_month_start = data_by_year_start.loc[data_by_year_start['startmonth'] == startmonth] startindex = data_by_month_start.index[0] data_by_year_end = data.loc[data['startyear'] == endyear] data_by_month_end = data_by_year_end.loc[data_by_year_end['startmonth'] == endmonth] endindex = data_by_month_end.index[-1] df = data.ix[startindex:endindex, :] df = df.reset_index(range(df.shape[0])) return df """ check input """ def check(yr, month): if yr == '2013': if month in [str(i) for i in range(7,13)]: return True elif yr == '2014': if month in [str(i) for i in range(1,13)]: return True elif yr == '2015': if month in [str(i) for i in range(1,11)]: return True else: return False
3ea97ed39eed4821ff05ff5a92e46dd5e9ed826d
flame4ost/Python-projects
/§4(77-119)/z89.py
562
3.890625
4
import math print("Задание 88 а ") a = input("Введите число a ") a = int(a) b = input("Введите число b ") b = int(b) print("a = ", a) print("b = ", b) while (a and b): if a>=b: a = a-b elif(b>=a): b = b-a print("Результат",b) print("Задание 88 б") def gcd(a,b): while(b>0): a,b=b,a%b return a def lcm(x,y): return (x*y)//gcd(x,y) a = int(input("Введите число a ")) b = int(input("Введите число b ")) print("Кратное = ",lcm(a,b))
b20766dfda3dc01f17aa2750330a0567325345db
shubhamkanade/Niyander-Python
/Multiplication.py
107
3.765625
4
def multiply(b,c): mul=b*c; return mul result=multiply(4,5) print("the multiplication is "+str(result))
0e7da2ec5944235ea6b5b8b811127f7237254e6f
LZY2006/A-poker-small-game-emulator
/Poker1.py
2,371
3.53125
4
# A 2 3 4 5 6 7 8 9 10 J Q K JOKER JOKER # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import random import time def step(x, _list): global desktop, one, another desktop.append(x) if _list == "one": if x in desktop[:-1]: pos = desktop[:-1].index(x) for i in desktop[pos:]: one.append(i) desktop = desktop[:pos] return True elif (x == 14) or (x == 15): for j in desktop: one.append(j) desktop = [] return True return False elif _list == "another": if x in desktop[:-1]: pos = desktop[:-1].index(x) for i in desktop[pos:]: another.append(i) desktop = desktop[:pos] return True elif (x == 14) or (x == 15): for j in desktop: another.append(j) desktop = [] return True return False else: raise ValueError cards = [1,2,3,4,5,6,7,8,9,10,11,12,13] * 4 + [14,15] random.seed(time.time()) random.shuffle(cards) one = cards[:27].copy() another = cards[27:].copy() desktop = [] # index = 0 result = [] index = 0 random.seed(time.time()) random.shuffle(cards) one = cards[:27].copy() another = cards[27:].copy() desktop = [] #result = [] def main(): global cards, one, another, desktop, result, index cards = [1,2,3,4,5,6,7,8,9,10,11,12,13] * 4 + [14,15] random.seed(time.time()) random.shuffle(cards) one = cards[:27].copy() another = cards[27:].copy() desktop = [] # index = 0 result = [] index = 0 random.seed(time.time()) random.shuffle(cards) one = cards[:27].copy() another = cards[27:].copy() desktop = [] while True: try: x = one.pop(0) while step(x, "one"): x = one.pop(0) y = another.pop(0) while step(y, "another"): y = another.pop(0) #print(desktop, x, y) index += 1 except IndexError: break if index > 1000: break ##if another == []: ## print(index, "one") ##elif one == []: ## print(index, "another") ##else: ## print("平")
3539f9a0704c66f35e82730a38ec7fbf5dfe0673
MihailSolomnikov/Mihail
/main.py
1,098
3.6875
4
from __future__ import annotations from abc import ABC, abstractmethod class Abiturient(ABC): @abstractmethod def factory_method(self): pass def some_operation(self) -> str: # Вызываем фабричный метод, чтобы получить объект-продукт. product = self.factory_method() # Далее, работаем с этим продуктом. result = f"Creator: worked with {product.operation()}" return result class Student(Abiturient): def factory_method(self) -> ZaoStudent: return Student_one() class ZaoStudent(ABC): @abstractmethod def operation(self) -> str: pass class Student_one(ZaoStudent): def operation(self) -> str: return "{Result of the Student_one is ZaoStudent}" def client_code(creator: Abiturient) -> None: print(f"Client: it still works.\n" f"{creator.some_operation()}", end="") if __name__ == "__main__": print("App: Launched") client_code(Student())
e638bb9170ef377411bdcaba3f82d17d3fda0485
cmonnom/Ped_Endocrine_Risk_Assessment
/date_helper.py
720
3.84375
4
from datetime import datetime from datetime import timedelta # split dates month, day, year = [int(s) for s in "7/2/2014".split("/")] print(month, day, year) # testing dates f_date = datetime(year, month, day) l_date = datetime(2014, 7, 11) # difference between dates diff_date = l_date - f_date print(diff_date) # adding days to a date later_date = f_date + timedelta(days=diff_date.days) # reformat to get a date field later_date_formatted = str(later_date.month) + "/" + str(later_date.day) + "/" + str(later_date.year) print(later_date_formatted) #code logic: # extract DOB # extract admission date # calculate the diff # set DOB to 1/1/1800 # add the diff to new DOB # replace DOB and admission dates by new dates
3169ff3ba355164dff2955e06d9d5fe0114e7c7a
Harshad06/Python_programs
/Higher complexity programs/sumofTwoNums01.py
416
3.734375
4
# sum 10 for adjacent 2 numbers?? x = [3, 2, 4, 6, 5, 9, 1, 12, 10] for i in range(len(x)-1): if x[i] + x[i+1] == 10: print(f'Numbers are: {x[i]} & {x[i+1]}') ''' output:- # Numbers are: 4 & 6 # Numbers are: 9 & 1 ------------------------------- error if :- if x[i] + x[i+1] == 10: IndexError: list index out of range it will take last element + 1, so it will OutOfIndex Error. '''
b53a0ac42858a7acab8f3920688a39993c6e0b6c
ynXiang/LeetCode
/563.BinaryTreeTilt/solution.py
1,069
3.71875
4
#https://discuss.leetcode.com/topic/87208/python-simple-with-explanation # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ return self.tiltWithSum(root)[0] def tiltWithSum(self, root): #return totel tilt of root and total sum of nodes including root if not root: return 0, 0 elif not root.left and not root.right: return 0, root.val elif not root.left: t, s = self.tiltWithSum(root.right) return t + abs(s), s + root.val elif not root.right: t, s = self.tiltWithSum(root.left) return t + abs(s), s + root.val else: tl, sl = self.tiltWithSum(root.left) tr, sr = self.tiltWithSum(root.right) return tl + tr + abs(sl -sr), sl + sr + root.val
00b65f36fd04c3bdcdd7fc59064e232f8dbdd50a
Renmusxd/PerturbationLib
/PerturbationLib/Symmetries.py
5,271
4
4
from abc import ABCMeta, abstractmethod from typing import Sequence, Tuple class Symmetry(metaclass=ABCMeta): """ A class containing information as to how to combine and calculate representations. Multiplets are stored in (a,b,c...) notation to remove ambiguity. A conversion method will be implemented for each class. """ def __init__(self, name: str, multiplets: Sequence[Tuple[int, ...]]): """ Create a symmetry :param name: unique identifier for symmetry :param multiplets: sum of multiplets (i.e. (1) + (3) + ...) """ self.name = name if multiplets is None: self.multiplets = [self.singletRepr()] else: self.multiplets = list(multiplets) def combine(self, sym: 'Symmetry') -> 'Symmetry': """ Combine a given symmetry with another symmetry :param sym: other U(N) with same N :return: new U(N) with sum of multiplets """ if self.matchesSymmetry(sym): mapRepr = [] for r1 in self.multiplets: for r2 in sym.multiplets: mapRepr += self.combineRepr(r1, r2) return self.constructWithNewRepr(mapRepr) raise Exception("Symmetries do not match: "+self.name+", "+sym.name) def singlet(self) -> 'Symmetry': """ Gives a singlet of the given group :return: """ return self.constructWithNewRepr([self.singletRepr()]) def inverse(self) -> 'Symmetry': """ Gives the conjugate representation :return: """ return self.constructWithNewRepr(self.inverseRepr()) def __call__(self, *args: Tuple[int, ...]) -> 'Symmetry': return self.constructWithNewRepr(args) @abstractmethod def constructWithNewRepr(self, newrepr: Sequence[Tuple[int, ...]]) -> 'Symmetry': """ Create a new version of this symmetry with new representations. :param newrepr: new representations :return: Symmetry with new representations """ raise Exception("Method was not overridden") @abstractmethod def combineRepr(self, r1: Tuple[int, ...], r2: Tuple[int, ...]) -> Tuple[int, ...]: """ Combines two representations of the symmetry. :return: [combined repr] """ raise Exception("Method was not overridden") @abstractmethod def containsSinglet(self) -> bool: """ :return: true if repr contains a singlet """ raise Exception("Method was not overridden") @abstractmethod def singletRepr(self) -> Tuple[int, ...]: """ Gives a singlet representation of the given group :return: """ raise Exception("Method was not overridden") @abstractmethod def inverseRepr(self) -> Sequence[Tuple[int, ...]]: """ Gives the conjugate representation representation/multiplets :return: """ raise Exception("Method was not overridden") @abstractmethod def matchesSymmetry(self, sym: 'Symmetry') -> bool: """ True/False if symmetries may be combined. :param sym: :return: """ return self.name == sym.name def __repr__(self): return self.name def _latex(self, *args): return self.__repr__() def _repr_latex(self): return "$"+self._latex()+"$" class U(Symmetry): """ U(N) symmetry """ def __init__(self, N: int, name: str = None, multiplets: Sequence[Tuple[int, ...]] = None): self.N = N super().__init__(name or 'U('+str(N)+')', multiplets) if N != 1: raise Exception("U(N>1) not yet implemented") def constructWithNewRepr(self, newrepr: Sequence[Tuple[int, ...]]) -> 'U': """ Create a new version of this symmetry with new representations. :param newrepr: new representations :return: Symmetry with new representations """ return U(self.N, self.name, newrepr) def combineRepr(self, r1, r2) -> Sequence[Tuple[int, ...]]: """ Combines the multiplets for two U(N) symmetries, returns new multiplet :param r1: :param r2: :return: """ if self.N == 1: return [(r1[0] + r2[0],)] else: raise Exception("U(N>1) not yet implemented") def containsSinglet(self) -> bool: if self.N == 1: return (0,) in self.multiplets else: raise Exception("U(N>1) not yet implemented") def singletRepr(self) -> Tuple[int, ...]: if self.N == 1: return 0, raise Exception("U(N>1) not yet implemented") def inverseRepr(self) -> 'Sequence[Tuple[int]]': if self.N == 1: return [(-x[0],) for x in self.multiplets] else: raise Exception("U(N>1) not yet implemented") def matchesSymmetry(self, sym: 'Symmetry') -> bool: if isinstance(sym, U): return self.name == sym.name and self.N == sym.N return False def __repr__(self): return "U("+str(self.N)+"){"+(" + ".join([str(x) for x in self.multiplets]))+"}"
3107407ba493e28a9d9b9ac4a6eec8c851a7d2e9
auntaru/mypycharms
/importcsv7function.py
951
3.59375
4
# https://pythonspot.com/reading-csv-files-in-python/ # https://pythonspot.com/category/database/ # https://pythonspot.com/en/mysql-with-python # https://pythonspot.com/en/python-database-postgresql/ # https://jakevdp.github.io/PythonDataScienceHandbook/03.10-working-with-strings.html import csv import pandas as pd def readMyFile(filename): column1 = [] column2 = [] column3 = [] column4 = [] with open(filename) as csvDataFile: csvReader = csv.reader(csvDataFile, delimiter=';') for row in csvReader: column1.append(row[0]) column2.append(row[1]) column3.append(row[2]) column4.append(row[3]) return column1, column2, column3, column4 servers, ports , databases, users = readMyFile('ALLPRIVILEGESModifyMySQL3col.csv.txt') names = pd.Series(users) usersip=names.str.split('@') print(servers) print(ports) print(databases) # print(users) print(usersip)
c6492bd31d9d28f50ebc3a5d8b7e0aaed0eae436
vijama1/codevita
/automorphic.py
327
3.59375
4
inp=input("Enter the number") intinp=int(inp) list=[] list1=[] list2=[] for i in inp: list.append(i) length=len(list) square=intinp*intinp strsquare=str(square) for j in strsquare: list1.append(j) list2=list1[-length:] num=int(''.join(list2)) if num==intinp: print("Automorphic") else: print("Not automorphic")
ed5a0b99588888098db4ef762dd864c568f73b2a
SleepwalkerCh/Leetcode-
/77.py
674
3.5
4
#77. Combinations #简单的全排列 class Solution: def combine(self, n: int, k: int) -> List[List[int]]: result=[] self.result=result nums=[x+1 for x in range(n-1)] self.Combination(nums,k,[]) return self.result def Combination(self,nums,num,res): if num==0: self.result.append(res[:]) for i in range(len(nums)): res.append(nums[i]) self.Combination(nums[i+1:],num-1,res) del(res[-1]) #Runtime: 696 ms, faster than 20.81% of Python3 online submissions for Combinations. #Memory Usage: 15.3 MB, less than 19.18% of Python3 online submissions for Combinations.
6aeef53d6112d30af0fc7609a257fc54c16bfdf9
michelman2/RigolDS1000Z
/code/Rigol_Lib/__init__.py
646
3.59375
4
import sys import os from pathlib import Path """ The file makes paths avaiable to python interpreter has to be added before using a project hierarchy """ def add_subfolder_to_path( project_base_folder): """ Function iterates over all folders and subfolders of current folder and add everything to the path """ for x in os.walk(project_base_folder): folder_subfolders = (x[0]) if(folder_subfolders in sys.path): pass else: sys.path.insert(1 , folder_subfolders) path = Path(os.getcwd()).parent print(path) add_subfolder_to_path(path)
5e6892111a1e6da698b0b00b6b6f6988d51c8a14
jes5918/TIL
/Algorithm/SWEA/파이썬SW문제해결 String/범/4861.py
803
3.5
4
import numpy as np def horizontal(x, n, m): result = '' for i in x: for j in range(n-m+1): a = i[j:j+m] for k in range(m//2): if a[k] != a[-(k+1)]: break else: result += a return result def vertical(a, n, m): result = np.array(a) for x in range(n): for y in range(n-m+1): for i in range(m//2): if a[x][y] != a[x][m-y]: break else: re = result[x:(x-1),y:(m-y)] return result for t in range(1, int(input())+1): N, M = map(int, input().split()) arr = [input() for i in range(N)] res = horizontal(arr, N, M) if res == False: res = vertical(arr, N, M) print(f'#{t} {res}')
5987a40144dce5447965eae0975aa77251b49a1c
AnshulDasyam/python
/syntax/Summation.py
125
3.984375
4
"""Sum of first n natural numbers""" n = int(input("Summation of ")) a = 0 b = 0 while a < n : a +=1 b += a print(b)
108e5fd5e69e22f430c198b47e6ad18e961843be
permCoding/elective-course
/py/meeting-4-task-27/task-21.py
107
3.578125
4
def f(x): return 2*x*x+3*x+2 k = int(input()) i = 15 while (i > 0 and f(i) > k): i -= 1 print(i)
f4f71572de30c2c6091b0f985bb2b1526c6ca390
aman-singh7/training.computerscience.algorithms-datastructures
/09-problems/lc_150_evaluate_reverse_polish_notation.py
798
3.90625
4
""" 1. Problem Summary / Clarifications / TDD: ["2", "1", "+", "3", "*"] 9 5 -208 """ class Solution: def __init__(self): self.operators = { "+": lambda b, a: a + b, "-": lambda b, a: a - b, "/": lambda b, a: int(a / b), "*": lambda b, a: a * b } def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token in self.operators: stack.append(self.operators[token](stack.pop(), stack.pop())) else: stack.append(int(token)) return stack[-1]
951cb94db2bb676ea0c05bc72ce316f5c103ac7b
Raymond-Zhu/CSC113_Project_1
/battle.py
2,000
3.765625
4
from status import player_status, battle_status #battle_status checks the status of everyone after someone makes a turn. If all enemy hp is 0 or player's hp is 0, it returns false to break the loop ending the battle import random import textwrap def battle(player,enemies,inventory): for enemy in enemies: print("A " + enemy.name + " has appeared.") enemy_count = len(enemies) delay = input("\nPress enter to continue...") status = True while(status): choice = input(textwrap.dedent(""" What do you want to do? 0 - Attack 1 - Magic 2 - Skills 3 - Items """)) if choice == "0": player.attack(enemies) elif choice == "1": player.magic(enemies) elif choice == "2": player.skill(enemies) elif choice == "3": player.use_potion(inventory) status = battle_status(player,enemies) delay = input("\nPress enter to continue...\n") if len(enemies) is not 0: for enemy in enemies: enemy.attack(player) status = battle_status(player,enemies) delay = input("\nPress enter to continue...\n") #Returns when you died if player.hp <= 0: return player print("You have gained %d experience.\n" % (enemy_count)) for x in range(0,enemy_count): player.hp += 1 player.full_hp += 1 player.mp += 1 player.full_mp += 1 player.atk += 1 player.matk += 1 player.defense += 1 player_status(player) #Random potion drop drop = random.randrange(0,4) if drop == 0: inventory['Health Potion'] += 1 print("You have obtained a Health Potion!\n") elif drop == 2: inventory['Mana Potion'] += 1 print("You have obtained a Mana Potion!\n") return player
eaf64c5ce602b2c608de00f3eb1d9f3ed05d3b24
EdwinSantos/EECS-4088
/flask/games/__game.py
5,082
3.578125
4
#!/usr/bin/python3 from copy import deepcopy, copy from abc import ABC, abstractmethod from queue import Queue, PriorityQueue from collections import OrderedDict, deque class Game(ABC): class Ranks(): ''' The ranks object is used by the display_game class to display standings. Its functionally a wrapper for a deque but exists as to define a function that expects a "Rank" object vs a "deque" object which is a common class. ''' def __init__(self): ''' Initializes Ranks as a deque(). ''' self.__ranks = deque() def prepend(self, player): ''' Prepends player to ranks. ''' self.__ranks.appendleft(player) def append(self, player): ''' Appends player to ranks. ''' self.__ranks.append(player) def __iter__(self): ''' Makes ranks iterable. ''' for item in self.__ranks: yield item @property def ranks(self): ''' Public accessor for private object __ranks ''' return self.__ranks def __init__(self, players, default, **kwargs): ''' Sets up the games default parameters. ''' self.state = {} super().__init__() self.nocopy = list(kwargs.keys()) self.socketio = kwargs.get('socketio', None) self.display_game = kwargs.get('display_game', None) self.__players = players self.__name__ = self.__class__.__name__ print("New "+self.__name__+" Started") self.active = True self.ranks = self.Ranks() self.state['players'] = OrderedDict() for player in players: self.state['players'][player] = copy(default) self.__active_players = len(list(players)) def __deepcopy__(self, memo): ''' Redefines deepcopy to not include to not deepcopy private objects and items produced by optional arguments. ''' cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): if k not in self.nocopy and not k.startswith('_'): setattr(result, k, deepcopy(v, memo)) return result @abstractmethod def display(self): ''' Abstract method display forces the child to redefine it. Used to display data to the console. ''' pass @abstractmethod def run_game(self): ''' Abstract method run_game forces the child to redefine it. Current version is only usable by calling super from child. ''' if self.__active_players < 1: self.end_game() def end_game(self): ''' Signal for ending a game. ''' self.active = False self.rank_players() self.display() if self.display_game is not None: self.display_game.update(self.ranks) self.socketio.sleep(3) print("Game Over") if self.socketio is not None: self.socketio.emit('gameOver', broadcast=True) @property def players(self): ''' Public accessor for __players ''' return self.__players @property def deepcopy(self): ''' Allows functions in game to call obj.deepcopy without importing deepcopy. ''' return deepcopy(self) def print_standings(self): ''' Prints standings. ''' print("Standings") for i, item in enumerate(self.ranks, 1): print(str(i) + ": " + str(item)) def rank_players(self): ''' Function for ranking players. Stores data in a priority queue to heapsort it. ''' results = PriorityQueue() for player, stats in self.state['players'].items(): results.put((stats['score'], player)) while not results.empty(): self.ranks.prepend(results.get()[1]) def remove_player(self, player=None): ''' Decrements player count if a player drops from a game. ''' self.__active_players -= 1 print("players left: " + str(self.__active_players)) def add_player(self, player=None): ''' Increments player if a player rejoins game. ''' self.__active_players += 1 print("players joined: " + str(self.__active_players)) def check_alive(self, player): ''' Checks if a player is alive in the current game. ''' if player is not None: hp = self.state['players'][player].get("hp") print(hp) if hp is not None and hp == "dead": return False return True
09ff4026527f0c110fa969ae08996c64df0ae69b
SpencerBurt/Minesweeper-game
/functions.py
5,611
4.0625
4
import board class Functions: """ Provides some of the utility functions for printing and interacting with the gameboard. """ @staticmethod def print_board(board:board.Board): """ Prints the gameboard :param board: The gameboard that will be printed :type board: Board :returns: void """ for y in range(board.ydim): for x in range(board.xdim): print(board.gameboard[y * board.xdim + x], end= '') print() @staticmethod def reveal_space(board:board.Board, xloc:int, yloc:int): """ Decides whether or not to reveal a space on the board given the user's input :param board: The board :type board: Board :param xloc: The x location to be checked :type xloc: int :param yloc: The y location to be checked :type yloc: int :returns: False if the move results in a loss and True otherwise """ space = board.gameboard[yloc * board.xdim + xloc] if space.is_marked: Functions.reveal_marked() return True elif space.is_bomb: board.is_lost = True return False elif not space.is_hidden: Functions.reveal_revealed() return True else: Functions.reveal_zeros(board, xloc, yloc, space) return True # Note: the function declaration sacrifices some simplicity to avoid having to import the space file, this could be simplified later on if problems arise. @staticmethod def reveal_zeros(board:board.Board, xloc:int, yloc:int, space:board.space.Space): """ Reveals a given space. Reveals the surrounding spaces if it is zero. :param board: The board :type board: Board :param xloc: The x location of the space being revealed :type xloc: int :param yloc: The y location of the space being revealed :type yloc: int :param space: The space being revealed, determined by the reveal_space function :type space: Space :returns: void """ space.is_hidden = False if space.value == 0: for y in range(-1,2): if (yloc + y != -1) and (yloc + y != board.ydim): for x in range(-1,2): location = board.gameboard[(yloc + y) * board.xdim + (xloc + x)] if (xloc + x != -1) and (xloc + x != board.xdim) and not location.is_bomb: location.is_hidden = False @staticmethod def check_won(board:board.Board): """ Checks if the game has been won. :param board: The board :type board: Board :returns: True if the game is won, False otherwise """ is_won = True for yloc in range(board.ydim): for xloc in range(board.xdim): location = board.gameboard[yloc * board.xdim + xloc] if location.is_hidden and not location.is_bomb: is_won = False board.is_won = is_won return is_won @staticmethod def reveal(gameboard:board.Board): """ Collects input and reveals a space based upon it. :param gameboard: The board :type board: Board :returns: False if the move resulted in a loss, True otherwise """ revealed = False while not revealed: xloc = int(input('Enter x location: \n')) yloc = int(input('Enter y location: \n')) if (xloc >= gameboard.xdim or yloc >= gameboard.ydim): print('Incorrect input, space is out of bounds') continue if Functions.reveal_space(gameboard, xloc, yloc): return True else: return False @staticmethod def mark(gameboard:board.Board): """ Collects input and marks a space based upon it. :param gameboard: The board :type gameboard: Board :returns: void """ marked = False while not marked: xloc = int(input('Enter x location: \n')) yloc = int(input('Enter y location: \n')) if (xloc >= gameboard.xdim or yloc >= gameboard.ydim): print('Incorrect input, space is out of bounds') continue gameboard.mark_space(xloc, yloc) @staticmethod def move(gameboard:board.Board): """ Decides and executes the move types dictated by the user. :param gameboard: The board :type gameboard: Board :returns: True if the game will continue, false if the given move is the last in the game """ Functions.print_board(gameboard) move = input('[R] Reveal [M] Mark [Q] Quit\n') if move.capitalize() == "R": if Functions.reveal(gameboard): gameboard.is_lost = False return True else: gameboard.is_lost = True return True elif move.capitalize() == 'Q': return False elif move.capitalize() == 'M': Functions.mark(gameboard) return True else: print('Please enter a valid move') return True @staticmethod def reveal_marked(): print('Space is marked, unmark it to reveal.') @staticmethod def reveal_revealed(): print('Space is already revealed.')
f98979ada41ef6011297582c15c1e07c97a497be
xiao812/code
/temperature/world_population.py
632
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 22:25:21 2020 @author: w """ import json from test import get_country_code # 将数据加载到一个列表中 filename = 'population_data.json' with open(filename) as f: pop_data = json.load(f) # 打印每个国家2010年的人口 for pop_dict in pop_data: if pop_dict['Year'] == '2010': country_name = pop_dict['Country Name'] population = int(float(pop_dict['Value'])) code = get_country_code(country_name) if code: print(code + ": " +str(population)) else: print('ERROR - ' + country_name)
275c38a2a98831592c7e04dc2185f44119f7ae78
sdvacap/Python--Spring2020
/Restriction_enzyme.py
1,547
3.953125
4
#Restriction Enzyme #Sarah Vaca #March 02,2020 #ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT #The sequence contains a recognition site for the EcoRI restriction enzyme, which cuts at the motif G*AATTC (the position of the cut is indicated by an asterisk) #Write a program which will calculate the size of the two fragments that will be produced when the DNA sequence is digested with EcoRI ###STEP 1 #Create a variable for the sequence sequence=("ACTGATCGATTACGTATAGTAGAATTCTATCATACATATATATCGATGCGTTCAT") print(sequence) ###STEP 2 #Find the motif G*AATTC in the sequence and cut between G and A, to obtain two fragments position=sequence.find("GAATTC") #find the motif "GAATTC" inside the sequence RE=sequence.replace("GAATTC","G AATTC") #replace "GAATTC" for "G AATTC", so you will know were the RE will cut print(RE) #print the sequence with the space, you will see where the RE will cut fragments=RE.split(" ") #split the sequence with a space print(fragments[0]) #shows the first fragment print(fragments[1]) #shows the second fragment ###STEP 3 #Calcutate the size of the first fragment frag1=len(fragments[0]) #calculate the size of the first fragment print("The size of the first fragment is", frag1) #Calcutate the size of the second fragment frag2=len(fragments[0]) #calculate the size of the second fragment print("The size of the second fragment is", frag2)
d3b4ada695a2b2369fd0d96d5f5ef36c0d9c5a66
AlexanderRagnarsson/M
/Assignments/Assignment 10/Stringtolist.py
818
4.4375
4
def word_splitter(word): """ Takes a string and splits is up into words which it appends to a list when there is a space or comma and then returns the list """ return_list = [] append_word = '' #Appends word to list whenever there is a space or comma next for char in word: if char == ',' or char == ' ': return_list.append(append_word) append_word = '' else: append_word += char #We never append the word if we dont end with a space or comma so lets append it the the list if word[-1] != ' ' or word[-1] != ',': return_list.append(append_word) return return_list # The main program starts here the_string = input("Enter the string: ") # call your function here the_list = word_splitter(the_string) print(the_list)
26c32a657118a20adf804da60ecd7992af48a29e
me-and/project-euler
/pe050.py
1,467
3.640625
4
#!/usr/bin/env python3 ''' Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? ''' from itertools import count from prime import primes if __name__ == '__main__': best_length = 21 best_prime = 953 for start_idx in count(): if sum(primes[start_idx:start_idx + best_length + 1]) > 1000000: # The smallest sum of primes for this start point is over one # million, so we're not going to find any new results. break for end_idx in count(start_idx + best_length + 1): sum_of_primes = sum(primes[start_idx:end_idx]) if sum_of_primes > 1000000: # Over one million, so try the next start index. break if sum_of_primes in primes: # Better than anything we've seen before. We know it has to # have a longer sequence since the shortest sequence length # we'd loop over is longer than the previous best result. best_prime = sum_of_primes best_length = end_idx - start_idx print(best_prime)
7ccd87484275fa2b0d0d180da871a7cbe7bb4099
ovidubya/Coursework
/Python/Programs/assign5part2.py
879
3.734375
4
a = [] # The array with all positive numbers not including zero b = [] # The array with all negative numbers including zeros c = [] # The array with all numbers isDone = True while(isDone): x = int(input("Enter a num")) if(x == -9999): break if(x > 0): a.append(x) if(x <= 0): b.append(x) c.append(x) def listA(): totalA = 0 for i in a: totalA = totalA + i return totalA def listB(): totalB = 0 for j in b: totalB = totalB + j return totalB def listC(): totalC = 0 for k in c: totalC = totalC + k return totalC # Averages for each list avgPositive = str(float(listA()//len(a))) avgNegative = str(float(listB()//len(b))) avgAll = str(float(listC()//len(c))) print("{'AvgPositive': " + avgPositive + ", 'AvgNonPos': " + avgNegative + ", 'AvgAllNum': " + avgAll + "}")
5c507cfc5582665dd273d8b91b712f46803cc8e5
massey-high-school/2020-91896-7-assessment-zionapril
/2020-91896-7-assessment-zionapril-master/01_String_Checker.py
606
4.09375
4
# Functions goes here def string_checker(question, to_check): valid = False while not valid: response = input(question).lower() for item in to_check: if response == item: return response elif response == item[0]: return item print("Can only be square, rectangle, triangle, parallelogram or circle") # *** Main Routine starts here *** available_shapes = ["square", "rectangle", "triangle", "parallelogram", "circle"] ask_user = string_checker("Choose a shape to work out:", available_shapes) print(ask_user)
2bcdb5d533b002d8f61510073a0eb07458d72b6d
gdincu/py_thw
/4_File_Handling.py
2,098
4.34375
4
#Ex15 import sys filename = sys.argv[1] """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Read a File 'r' is the default mode. It opens a file for reading and reads the entire content of the file. """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" f=open(filename, "r") if f.mode == 'r': contents =f.read() print(contents) #readlines - used to read the contents of a file line by line fTemp = f.readlines() for x in fTemp: print(x) """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Adds to the file 'w' opens the file for writing. If the file doesn't exist it creates a new file. If the file exists it truncates the file. """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" f= open("template.txt","w+") print("Adds lines to the file: ") for i in range(10): f.write("This is line %d\r\n" % (i+1)) """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Create a new file 'x' creates a new file. If the file already exists, the operation fails. """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" f= open("newFile.txt",'x') """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Append Data to a File 'a' opens a file in append mode. If the file does not exist, it creates a new file """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" f=open(filename, "a+") for i in range(2): f.write("Appended line %d\r\n" % (i+1)) """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Truncate a file """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" #Opens the file & provides writing permission print("Opening the file....") txt = open(filename,'w+') #Truncates the file print("Truncating the file") txt.truncate() """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Close a file """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" target.close()
77046d8e99bf5b4d3c1b78f9d92a30d2cc2d34b0
stephnec/ExerciciosLista01-Python
/Ex05.py
284
3.671875
4
precoCombustivel = float(input("Digite o preço do litro do combustível: ")) valorDinheiro = float(input("Digite o valor em dinheiro que deseja pagar: ")) litrosTotal = valorDinheiro / precoCombustivel print("O total de litros a ser comprado é de " + str(litrosTotal) + " litros")