blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e313000d0ee70104ac49026c29e528d2d8754547
Arushi-V/PythonWithCM
/2021.08.05/ques_map.py
469
4.40625
4
# return cube of array using map function. inp = input("Enter array: ") print("type of inp: ",type(inp), inp) inp = inp.split() print("type of inp: ",type(inp), inp) inp_2 = [] for x in inp: inp_2.append(int(x)) print("type of inp_2: ",type(inp_2), inp_2) inp_3 = map(int, input("Enter array: ").split()) print("type of inp_3: ",type(inp_3), inp_3) result = list(inp_3) result = map(lambda x : x**3, result) result = list(result) print("Cube root :", result)
6cc7e67d4045d505a8c4d91dd42d62011efce42c
jmgamboa/coding-exercises
/easy/trees/sameTree.py
1,008
3.765625
4
# https://leetcode.com/problems/same-tree/ # 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 isSameTree(self, p_tree: TreeNode, q_tree: TreeNode) -> bool: p_list = [] q_list = [] def traverse(node, node2): if node.left.val != node2.left.val: return False if node.left and node2.left: traverse(node.left, node2.left) if node.right.val != node2.right.val: return False if node.right and node2.right: traverse(node.right, node2.right) return True res = traverse(p_tree, q_tree) return res t3 = TreeNode(1) t2 = TreeNode(2) t1 = TreeNode(1, left=t2, right=t3) import pdb; pdb.set_trace() y3 = TreeNode(2) y2 = TreeNode(1) y1 = TreeNode(1, t2, t3) Solution().isSameTree(t1, y1)
d1edece5338ee9d658c6803b593945782edf891f
Stefan1502/Practice-Python
/exercise 16.py
909
3.90625
4
# Write a password generator in Python. Be creative with how you generate passwords # - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. # The passwords should be random, generating a new password every time the user asks for a new password. # Include your run-time code in a main method. # Extra: # Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list. if __name__ == "__main__": import random import re low = ['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'] cap = [el.upper() for el in low] num = ['1','2','3','4','5','6','7','8','9'] sym = ['@','#','$','^','&','*','!','?'] alll = low + cap + num + sym pwd = ''.join([random.choice(alll) for el in range(random.choice(range(5,20)))]) print(pwd)
62b5936b4f907a5a672e112ca5a965a6dac0225c
KimDoKy/006793
/introcs-PartialSolutions/1.4/inversepermutation.py
1,214
3.734375
4
#----------------------------------------------------------------------- # inversepermutation.py #----------------------------------------------------------------------- import stdio import sys import stdarray # Accept a permutation of integers from the command line and write the # inverse permutation to standard output. # Accept the permutation. perm = [] for i in range(1, len(sys.argv)): perm += [int(sys.argv[i])] n = len(perm) # Make sure the permutation is valid. exists = stdarray.create1D(n, False) for i in range(n): if (perm[i] < 0) or (perm[i] >= n) or exists[perm[i]]: stdio.writeln("Not a permutation") sys.exit(0) exists[perm[i]] = True # Invert the permutation. permInverted = [0] * n for i in range(n): permInverted[perm[i]] = i # Write the inverted permutation. for element in permInverted: stdio.write(str(element) + ' ') stdio.writeln() #----------------------------------------------------------------------- # python inversepermutation.py 0 1 2 3 4 5 # 0 1 2 3 4 5 # python inversepermutation.py 5 4 3 2 1 0 # 5 4 3 2 1 0 # python inversepermutation.py 5 3 4 0 1 2 # 3 4 5 1 2 0 # python inversepermutation.py 1 2 3 4 5 # Not a permutation
1b44ab5230c48b00f88d1edbfd7a066759531b32
ChanceRbrts/Senior-Design-Game
/Default/ClassPuzzle2.py
865
3.78125
4
#Now, as you can see, classes have a whole #bunch of functions. The init function is #one that is called to create the object. #ClassPuzzle2 in this case is a subclass, #or a class that builds off a "super" class. #That's what (Solid) and Solid.__init__ does. #Now, this object is stubborn as a Solid #object, but as a Monster, it decides to finally move. from Solid import* from Monster import* class ClassPuzzle2(Solid): def __init__(self,oX=0,oY=0,oW=1,oH=1): Solid.__init__(self,oX,oY,oW,oH) self.name = "ClassPuzzle2" if (self.collision == "Solid"): self.image = pygame.image.load("Game/Sprites/AsymetricStoneBlock.png") self.codingStartVisible = [0,] self.codingEndVisible = [14,] def checkType(self): if (self.collision == "Solid"): pass elif (self.collision == "Monster"): self.dX = -1 def finishUpdate(self): self.x += self.dX
6efae1a8f0f00f1c68e2ffda94564098a7ac8903
xiao-xiaoming/DataStructure-BeautyOfAlgorithm
/16.heap/Heap.py
3,471
3.78125
4
# -*- coding: utf-8 -*- __author__ = 'xiaoxiaoming' class Heap: def __init__(self, heap_arr=None, type="max", sort_key=lambda x: x): if type == "min": self.cmp = lambda x, y: sort_key(x) < sort_key(y) else: self.cmp = lambda x, y: sort_key(x) > sort_key(y) if heap_arr is None: heap_arr = [] self.heap_arr = heap_arr # 从下标0开始存储数据 self.index = len(heap_arr) - 1 # 堆中最后一个元素的下标 self.rebuild_heap() def __len__(self): return self.index + 1 def rebuild_heap(self): """堆的构建角标从0开始, 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 最后一层叶子节点不需要进行堆化,故只要不是满二叉树,i//2就能从上层开始 """ for i in range((self.index - 1) >> 1, -1, -1): # 从数组最后一个元素开始依次从上往下堆化 self.heapify_up_to_down(self.index, i) def sort(self): for k in range(self.index, -1, -1): self.heap_arr[0], self.heap_arr[k] = self.heap_arr[k], self.heap_arr[0] self.heapify_up_to_down(k - 1, 0) def insert(self, data): self.index += 1 if self.index == len(self.heap_arr): self.heap_arr.append(data) else: self.heap_arr[self.index] = data self.heapify_down_to_top(self.index) def heapify_down_to_top(self, i): """自下往上堆化""" while ((i - 1) >> 1) >= 0 and self.cmp(self.heap_arr[i], self.heap_arr[(i - 1) >> 1]): # 交换下标为 i 和 父节点 i-1/2 的两个元素 j = (i - 1) >> 1 self.heap_arr[i], self.heap_arr[j] = self.heap_arr[j], self.heap_arr[i] i = (i - 1) >> 1 def heapify_up_to_down(self, n: int, i: int): """自上往下堆化""" pos = i while True: if i * 2 + 1 <= n and self.cmp(self.heap_arr[i * 2 + 1], self.heap_arr[i]): pos = i * 2 + 1 if i * 2 + 2 <= n and self.cmp(self.heap_arr[i * 2 + 2], self.heap_arr[pos]): pos = i * 2 + 2 if pos == i: break self.heap_arr[i], self.heap_arr[pos] = self.heap_arr[pos], self.heap_arr[i] i = pos def update_top(self, data): self.heap_arr[0] = data self.heapify_up_to_down(self.index, 0) def remove_top(self): if self.index == -1: return tmp = self.heap_arr[0] self.heap_arr[0] = self.heap_arr[self.index] self.index -= 1 self.heapify_up_to_down(self.index, 0) return tmp def get_top(self): if self.index == -1: return None return self.heap_arr[0] def get_all(self): return self.heap_arr[:self.index + 1] def __repr__(self): return str(self.heap_arr[:self.index + 1]) if __name__ == "__main__": # 数组的第一个元素不存储数据 a = [6, 3, 4, 0, 9, 2, 7, 5, -2, 8, 1, 6, 10] heap = Heap(a, type="max") heap.sort() print(heap.get_all()) heap = Heap(a, type="min") heap.sort() print(heap.get_all()) heap = Heap(type="min") k = 3 for e in a: if heap.index == k: if e > heap.get_top(): heap.update_top(e) else: heap.insert(e) print(heap.get_all())
d7e942d7dea9767bde940670b5b66eb970f336bb
mhounsom/python-challenge
/PyBank/pybank_main.py
2,259
3.828125
4
import os import csv csvpath = os.path.join(".", "PyBank", "Resources", "budget_data.csv") monthly_revenue_change = [] date = [] total_revenue = 0 total_months = 0 greatest_increase = 0 greatest_increase_month = 0 greatest_decrease = 0 greatest_decrease_month = 0 with open(csvpath, newline = '') as csvfile: csvreader = csv.reader(csvfile, delimiter = ',') next(csvreader, None) csv_header = next(csvreader) previous_profit_loss = int(csv_header[1]) total_months = total_months + 1 total_revenue = total_revenue + int(csv_header[1]) for row in csvreader: total_months = total_months + 1 total_revenue = total_revenue + int(row[1]) monthly_change = int(row[1]) - previous_profit_loss monthly_revenue_change.append(monthly_change) previous_profit_loss = int(row[1]) date.append(row[0]) if int(row[1]) > greatest_increase: greatest_increase = int(row[1]) greatest_increase_month = row[0] if int(row[1]) < greatest_decrease: greatest_decrease = int(row[1]) greatest_decrease_month = row[0] high = max(monthly_revenue_change) low = min(monthly_revenue_change) average_change = round((sum(monthly_revenue_change)/len(monthly_revenue_change)), 2) print("Financial Analysis") print("-----------------------------------") print(f"Total Months: {total_months}") print(f"Total: ${total_revenue}") print(f"Average Change: ${average_change}") print(f"Greatest Increase in Profits: {greatest_increase_month} (${high})") print(f"Greatest Decrease in Profits: {greatest_decrease_month} (${low})") output_file = os.path.join(".", "PyBank", "analysis", "pybank_results.text") with open(output_file, 'w',) as txtfile: txtfile.write(f"Financial Analysis\n") txtfile.write(f"-----------------------------------\n") txtfile.write(f"Total Months: {total_months}\n") txtfile.write(f"Total: ${total_revenue}\n") txtfile.write(f"Average Change: ${average_change}\n") txtfile.write(f"Greatest Increase in Profits:, {greatest_increase_month}, (${high})\n") txtfile.write(f"Greatest Decrease in Profits:, {greatest_decrease_month}, (${low})\n")
3d4d4ab1810ea4a73ac904e6b2d6ef864b651e7c
papalagichen/leet-code
/0024 - Swap Nodes in Pairs.py
896
3.625
4
from ListBuilder import ListNode # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head prev, current, head = None, head, head.next while current and current.next: a, b, current = current, current.next, current.next.next if prev: prev.next = b a.next, b.next, prev = current, a, a return head if __name__ == '__main__': import Test import ListBuilder Test.test(Solution().swapPairs, [ (ListBuilder.build(1, 2, 3, 4), ListBuilder.build(2, 1, 4, 3)), (ListBuilder.build(1, 2, 3), ListBuilder.build(2, 1, 3)), (ListBuilder.build(1), ListBuilder.build(1)), ])
70fb5cca07bc4f71654504c674e55597eef6862f
diascreative/VaingloriousEye
/vaineye/ziptostate.py
6,502
3.8125
4
""" Converts zip codes to state codes. Also converts state codes to state names. """ # From data at: # http://www.novicksoftware.com/udfofweek/Vol2/T-SQL-UDF-Vol-2-Num-48-udf_Addr_Zip5ToST.htm def zip_to_state(zip): """Convert the zip or postal code to a state code. This returns None if it can't be converted""" if isinstance(zip, basestring): zip = zip.split('-', 1)[0] try: zip = int(zip, 10) except ValueError: return None if zip >= 99501 and zip <= 99950: return 'AK' elif zip >= 35004 and zip <= 36925: return 'AL' elif zip >= 71601 and zip <= 72959: return 'AR' elif zip >= 75502 and zip <= 75502: return 'AR' elif zip >= 85001 and zip <= 86556: return 'AZ' elif zip >= 90001 and zip <= 96162: return 'CA' elif zip >= 80001 and zip <= 81658: return 'CO' elif zip >= 6001 and zip <= 6389: return 'CT' elif zip >= 6401 and zip <= 6928: return 'CT' elif zip >= 20001 and zip <= 20039: return 'DC' elif zip >= 20042 and zip <= 20599: return 'DC' elif zip >= 20799 and zip <= 20799: return 'DC' elif zip >= 19701 and zip <= 19980: return 'DE' elif zip >= 32004 and zip <= 34997: return 'FL' elif zip >= 30001 and zip <= 31999: return 'GA' elif zip >= 39901 and zip <= 39901: return 'GA' elif zip >= 96701 and zip <= 96898: return 'HI' elif zip >= 50001 and zip <= 52809: return 'IA' elif zip >= 68119 and zip <= 68120: return 'IA' elif zip >= 83201 and zip <= 83876: return 'ID' elif zip >= 60001 and zip <= 62999: return 'IL' elif zip >= 46001 and zip <= 47997: return 'IN' elif zip >= 66002 and zip <= 67954: return 'KS' elif zip >= 40003 and zip <= 42788: return 'KY' elif zip >= 70001 and zip <= 71232: return 'LA' elif zip >= 71234 and zip <= 71497: return 'LA' elif zip >= 1001 and zip <= 2791: return 'MA' elif zip >= 5501 and zip <= 5544: return 'MA' elif zip >= 20331 and zip <= 20331: return 'MD' elif zip >= 20335 and zip <= 20797: return 'MD' elif zip >= 20812 and zip <= 21930: return 'MD' elif zip >= 3901 and zip <= 4992: return 'ME' elif zip >= 48001 and zip <= 49971: return 'MI' elif zip >= 55001 and zip <= 56763: return 'MN' elif zip >= 63001 and zip <= 65899: return 'MO' elif zip >= 38601 and zip <= 39776: return 'MS' elif zip >= 71233 and zip <= 71233: return 'MS' elif zip >= 59001 and zip <= 59937: return 'MT' elif zip >= 27006 and zip <= 28909: return 'NC' elif zip >= 58001 and zip <= 58856: return 'ND' elif zip >= 68001 and zip <= 68118: return 'NE' elif zip >= 68122 and zip <= 69367: return 'NE' elif zip >= 3031 and zip <= 3897: return 'NH' elif zip >= 7001 and zip <= 8989: return 'NJ' elif zip >= 87001 and zip <= 88441: return 'NM' elif zip >= 88901 and zip <= 89883: return 'NV' elif zip >= 6390 and zip <= 6390: return 'NY' elif zip >= 10001 and zip <= 14975: return 'NY' elif zip >= 43001 and zip <= 45999: return 'OH' elif zip >= 73001 and zip <= 73199: return 'OK' elif zip >= 73401 and zip <= 74966: return 'OK' elif zip >= 97001 and zip <= 97920: return 'OR' elif zip >= 15001 and zip <= 19640: return 'PA' elif zip >= 2801 and zip <= 2940: return 'RI' elif zip >= 29001 and zip <= 29948: return 'SC' elif zip >= 57001 and zip <= 57799: return 'SD' elif zip >= 37010 and zip <= 38589: return 'TN' elif zip >= 73301 and zip <= 73301: return 'TX' elif zip >= 75001 and zip <= 75501: return 'TX' elif zip >= 75503 and zip <= 79999: return 'TX' elif zip >= 88510 and zip <= 88589: return 'TX' elif zip >= 84001 and zip <= 84784: return 'UT' elif zip >= 20040 and zip <= 20041: return 'VA' elif zip >= 20040 and zip <= 20167: return 'VA' elif zip >= 20042 and zip <= 20042: return 'VA' elif zip >= 22001 and zip <= 24658: return 'VA' elif zip >= 5001 and zip <= 5495: return 'VT' elif zip >= 5601 and zip <= 5907: return 'VT' elif zip >= 98001 and zip <= 99403: return 'WA' elif zip >= 53001 and zip <= 54990: return 'WI' elif zip >= 24701 and zip <= 26886: return 'WV' elif zip >= 82001 and zip <= 83128: return 'WY' return None def unabbreviate_state(abbrev): """Given a state abbreviation, return the full state name""" return abbrev_to_state[abbrev].capitalize() state_to_abbrev = { 'ALABAMA': 'AL', 'ALASKA': 'AK', 'AMERICAN SAMOA': 'AS', 'ARIZONA': 'AZ', 'ARKANSAS': 'AR', 'CALIFORNIA': 'CA', 'COLORADO': 'CO', 'CONNECTICUT': 'CT', 'DELAWARE': 'DE', 'DISTRICT OF COLUMBIA': 'DC', 'FEDERATED STATES OF MICRONESIA': 'FM', 'FLORIDA': 'FL', 'GEORGIA': 'GA', 'GUAM': 'GU', 'HAWAII': 'HI', 'IDAHO': 'ID', 'ILLINOIS': 'IL', 'INDIANA': 'IN', 'IOWA': 'IA', 'KANSAS': 'KS', 'KENTUCKY': 'KY', 'LOUISIANA': 'LA', 'MAINE': 'ME', 'MARSHALL ISLANDS': 'MH', 'MARYLAND': 'MD', 'MASSACHUSETTS': 'MA', 'MICHIGAN': 'MI', 'MINNESOTA': 'MN', 'MISSISSIPPI': 'MS', 'MISSOURI': 'MO', 'MONTANA': 'MT', 'NEBRASKA': 'NE', 'NEVADA': 'NV', 'NEW HAMPSHIRE': 'NH', 'NEW JERSEY': 'NJ', 'NEW MEXICO': 'NM', 'NEW YORK': 'NY', 'NORTH CAROLINA': 'NC', 'NORTH DAKOTA': 'ND', 'NORTHERN MARIANA ISLANDS': 'MP', 'OHIO': 'OH', 'OKLAHOMA': 'OK', 'OREGON': 'OR', 'PALAU': 'PW', 'PENNSYLVANIA': 'PA', 'PUERTO RICO': 'PR', 'RHODE ISLAND': 'RI', 'SOUTH CAROLINA': 'SC', 'SOUTH DAKOTA': 'SD', 'TENNESSEE': 'TN', 'TEXAS': 'TX', 'UTAH': 'UT', 'VERMONT': 'VT', 'VIRGIN ISLANDS': 'VI', 'VIRGINIA': 'VA', 'WASHINGTON': 'WA', 'WEST VIRGINIA': 'WV', 'WISCONSIN': 'WI', 'WYOMING': 'WY', } abbrev_to_state = {} for name, abbrev in state_to_abbrev.items(): abbrev_to_state[abbrev] = name del name, abbrev
12f7d6752f849764ef414f74a38d57545a17e30c
omegachysis/arche-engine
/demo 003 - Interface Example.pyw
3,122
3.515625
4
#!/usr/bin/env python3 import arche log = arche.debug.log("main") def main(): log.info("starting demo 003") game = arche.Game(width = 1280, height = 800, fullscreen = False, titleName = "ArcheEngine Demo - Interface Example", frame = False, # don't show the os window stuff ) InterfaceExample().start() game.run() # Applications are used to organize various parts of your game. # They are analogous to PowerPoint slides or separate slides # in a slide show. class InterfaceExample(arche.Application): def __init__(self): super(InterfaceExample, self).__init__() # run this at the beginning of every class derivation self.backgroundColor = (50,0,0) # Create an 'x' button in the corner of the screen self.quitButton = arche.interface.SolidButton( # all widths and heights are in pixels width = 50, height = 30, # the reset color is the default color of the unselected button colorReset = (100,100,100), # the hover color is the color of the button when hilighting colorHover = (255,50,50), # the press color is the color when clicking the button colorPress = (255,150,150), # all applications inherit the 'game' attribute command = self.game.quit, # create a caption textObject = arche.Text( value = "X", # x and y values are parented attributes relative to the button center x = 0, y = 0, color = (255,255,255), size = 30, font = "font/consola.ttf"), ) # You can move sprites as much as you want after you create them. # You can set and get coordinates by 'left', 'right', 'top', 'bottom', # 'x', 'y', and 'rect' values. self.quitButton.right = self.game.width + 1 self.quitButton.top = -1 # You never have to name sprites like this, but it's a good idea self.quitButton.name = "quit button" # you must add sprites to the applications # with the 'addSprite' command before they appear! self.addSprite(self.quitButton) # Create a greeting text sprite self.greetingText = arche.Text( value = "Hello World! Press the X button in the upper right corner " + \ "of the screen to quit.", # the 'game.-prop' commands allow you to control coordinates based on # the resolution or screen size that the client has chosen to allow. # .50 means that it is centered on the screen proportional to that metric. x = self.game.xprop(.50), y = self.game.yprop(.50), color = (255,255,255), size = 20, font = "font/consola.ttf", ) self.addSprite(self.greetingText) if __name__ == "__main__": arche.debug.test(main)
ff5f112bd1ce80e7390fa1fb213775ccd3e6cf04
subodhss23/python_small_problems
/find_the_falsehood.py
365
4.0625
4
''' write a function that, given a list of values, returns the list of the values that are False ''' def find_the_falsehoods(lst): new_arr = [] for i in lst: if bool(i) == False: new_arr.append(i) return new_arr print(find_the_falsehoods([0, 1, 2, 3])) print(find_the_falsehoods(["", "a", "ab"])) print(find_the_falsehoods([]))
7613dfc5d95571789d74b42ba4a2588bb4620cd9
AsmitJoy/Python-Bible
/list comprehensions.py
403
3.96875
4
even_numbers = [x for x in range(1,101) if x%2 ==0] print("There are {} even numbers and they are {} ".format(len(even_numbers),even_numbers)) odd_numbers = [x for x in range(1,101) if x%2 !=0] print("There are {} odd numbers and they are {} ".format(len(odd_numbers),odd_numbers)) words = ["the","quick","brown","Jump","dog","lazy"] ans = [[w.upper(),w.lower(),len(w)] for w in words] print(ans)
91f6f93546e8240aff32445f1e68c11ccfe19d83
wwtang/code02
/tem.py
214
4.25
4
color = raw_input('please select the color: ') if color == "white" or color == "black": print "the color was black or white" elif color > "k" : print "the color start with letter after the 'K' in alphabet"
b9094f11272e7272b4f80ebc4f70280e2917bdf7
kumarUjjawal/python_problems
/one-away.py
909
3.6875
4
# Given two strings write a function to to check if it's one edit or zero edits away. def one_edit_different(s1, s2): if len(s1) == len(s2): return one_edit_replace(s1, s2) if len(s1) + 1 == len(s2): return one_edit_insert(s2, s2) if len(s1) - 1 == len(s2): return one_edit_insert(s2, s1) return False def one_edit_replace(s1, s2): edited = False for c1, c2 in zip(s1, s2): if c1 != c2: if edited: return False edited = True return True def one_edit_insert(s1, s2): edited = False i, j = 0,0 while i < len(s1) and j < len(s2): if s1[i] != s2[j]: if edited: return False edited = True j += 1 else: i += 1 j += 1 return True s1, s2 = "pale", "ple" print(one_edit_different(s1, s2))
a7d99257d530c5d04267b1b979f170020300826c
soulgchoi/Algorithm
/Programmers/Level 3/섬 연결하기2.py
1,046
3.5625
4
def solution(n, costs): parent = {} rank = {} def make_set(v): parent[v] = v rank[v] = 0 def find(v): if parent[v] != v: parent[v] = find(parent[v]) return parent[v] def union(v, u): root1 = find(v) root2 = find(u) if root1 != root2: if rank[root1] > rank[root2]: parent[root2] = root1 else: parent[root1] = root2 if rank[root1] == rank[root2]: rank[root2] += 1 def kruskal(graph): for v in graph['vertices']: make_set(v) mst = 0 edges = graph['edges'] edges.sort(key=lambda x: x[2]) for edge in edges: v, u, weight = edge if find(v) != find(u): union(v, u) mst += weight return mst graph = { 'vertices': list(range(n)), 'edges': costs } answer = kruskal(graph) return answer print(solution(4, [[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 1], [2, 3, 8]])) # 4 print(solution(5, [[0, 1, 5], [1, 2, 3], [2, 3, 3], [3, 1, 2], [3, 0, 4], [2, 4, 6], [4, 0, 7]])) # 15 print(solution(5, [[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 3], [2, 3, 8], [3, 4, 1]])) # 7
644a5841ede807b19d8ca13e4ff26320f5c9b914
AlexAndrDoom/lesson1
/hello.py
309
4.03125
4
print("ПРивет. мир") a=2 b=0.5 print(a+b) a=2.5 b=0.5 print(a-b) a=2 b=2 print(a/b) name= "Alex" b='привет ' x="Hello, {}!".format(name) x=f"Hello, {name}!" print(x) v=input("число") z=int(v)+ 10 print(z) a=int(input()) b=int(input()) print(float(a+b)) d=int(4/3)*3 print(int(d))
9ccb164280db027f0acf217b95223a07249cfa83
melission/Timus.ru
/1607.py
854
3.84375
4
customerPrice, customerProposal, driverPrice, driverProposal = input().strip().split() customerPrice, customerProposal = int(customerPrice), int(customerProposal) driverPrice, driverProposal = int(driverPrice), int(driverProposal) finishPrice = 0 changed = True acc = True if customerPrice > driverPrice: finishPrice = customerPrice acc = False while acc: if customerPrice + customerProposal < driverPrice: customerPrice = customerPrice + customerProposal finishPrice = customerPrice # print(customerPrice) if customerPrice + customerProposal > driverPrice: finishPrice = driverPrice if customerPrice + customerProposal < driverPrice: driverPrice = driverPrice - driverProposal finishPrice = driverPrice # print(driverPrice) else: acc = False print(finishPrice)
40e814728a51f69746a77108be2b1aab9430fb63
ll996075dd/xuexi
/day-1-4.py
176
3.640625
4
import string s = input('请输入一个字符串:\n') letters = 0 i =0 while i < len(s): c = s[i] i += 1 if c.isalpha(): letters += 1 print ('%d' %letters)
f0560becc21541dfdfa14130878f3a9af9a0b570
hsouporto/Note-Everyday
/Slides_Note/Stanford_Algorithms/PythonCode/Course1/Week1/sortComp.py
3,222
3.9375
4
# -*- coding: utf-8 -*- """ @author: HYJ """ import time ## MergeSort def merge(left, right): result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) # 只要 left 或者 right 非空 if left: result += left if right: result += right return result def mergeSort(array): sortedArray = [] arrayLen = len(array) if arrayLen <= 1: return array mid = arrayLen // 2 left = array[:mid] right = array[mid:] left = mergeSort(left) right = mergeSort(right) sortedArray = merge(left, right) return sortedArray ## Selection Sort # 就是每次找到最小的,然后一直和开头进行交换 def selectionSort(array): arrayLen = len(array) if arrayLen <= 1: return array for i in range(arrayLen-1): minIndex = i # <= i的数值是已经排序的 for j in range(i+1,arrayLen): if array[j] < array[minIndex]: minIndex = j array[i], array[minIndex] = array[minIndex], array[i] return array ## Bubble Sort # 就是相当于一直翻转,最后一个即为当前的最大值 def bubbleSort(array): arrayLen = len(array) if arrayLen <= 1: return array for i in range(arrayLen-1): for j in range(arrayLen-i-1): if array[j] > array[j+1]: array[j+1], array[j] = array[j], array[j+1] return array ## In-place Quick Sort def partition(array): arrayLen = len(array) pivotIndex = 0 storeIndex = 0 pivot = array[:pivotIndex+1] for i in range(storeIndex+1, arrayLen): if array[i] < array[pivotIndex]: storeIndex += 1 array[i], array[storeIndex] = array[storeIndex], array[i] array[storeIndex], array[pivotIndex] = array[pivotIndex], array[storeIndex] lo = array[:storeIndex] hi = array[storeIndex+1:] return lo, hi, pivot def quickSort(array): sortedArray = [] arrayLen = len(array) if arrayLen <= 1: return array if arrayLen == 2: if array[1] < array[0]: array[0], array[1] = array[1], array[0] return array lo, hi, pivot = partition(array) lo = quickSort(lo) hi = quickSort(hi) sortedArray = lo sortedArray.extend(pivot) sortedArray.extend(hi) return sortedArray # 可以将输入直接转列表 originArray = eval(input('input an array: ')) start1 = time.clock() sortedArray1 = mergeSort(originArray) end1 = time.clock() start2 = time.clock() sortedArray2 = selectionSort(originArray) end2 = time.clock() start3 = time.clock() sortedArray3 = selectionSort(originArray) end3 = time.clock() start4 = time.clock() sortedArray4 = quickSort(originArray) end4 = time.clock() print('Sorted array is {}'.format(sortedArray4)) print('Merge Sort takes {} sec'.format(end1-start1)) print('Selection Sort takes {} sec'.format(end2-start2)) print('Bubble Sort takes {} sec'.format(end3-start3)) print('Quick Sort takes {} sec'.format(end3-start3))
ddf3e689bcac29fac17f47ff9356d8434173b0a5
Grammer/stepic_python
/23.py
121
3.8125
4
summ = 0 num = 0 while True: a = int(input()) summ += a num += a*a if summ == 0: break print(num)
041c7cecb4f11bafd6833dc6f57185974d29b522
Aradhya910/numberguesser
/numberguesser.py
868
4.125
4
import random number = random.randint(1, 10) player_name = input('What is your name? ') number_of_guesses = 0 print('''Hello! ''' + player_name + " Let's start the game, Press W for instructions. " ) instructions = input('') if instructions.upper() == 'W': print(''' You have to guess a random number between 1 to 10 You only have 5 number of guesses! ''') else: print("I did not understand that, sorry ") quit() while number_of_guesses <= 4: guess = int(input()) number_of_guesses += 1 if guess < number: print('The guess is low. ') if guess > number: print('The guess is high. ') if guess == number: break if guess == number: print('You guessed the number in ' + str(number_of_guesses) + ' tries! ') else: print('Alas you lost! The number was ' + str(number) + '. ')
843831d46afe9c1a3de0b7491c6fe310693e37ab
stefanFramework/kivy
/coliders.py
592
3.6875
4
from abc import ABC, abstractmethod from characters.characters import Character class CollidDetector: @staticmethod def collides(character1: Character, character2: Character) -> bool: if character1.position.x < (character2.position.x + character2.size.width) and \ (character1.position.x + character1.size.width) > character2.position.x and \ character1.position.y < (character2.position.y + character2.size.height) and \ character1.position.y + character1.size.height > character2.position.y: return True return False
0a41a13b723da9f471faff33d0e923a4ec1a1175
mokkacuka/datascience
/scatter-plot.py
1,065
4.3125
4
# IMPORT CSV FILE INTO A DATAFRAME # DRAW A PLOT FROM TWO VARIABLES OF DATAFRAME # Import all libraries needed for the tutorial import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # Create a Dataframe from a source CSV file df = pd.read_csv('yourFile.csv') df # Round a variable of the Dataframe - Not mandatory (depends on variable type) # Replace variable1 by the name of a variable of source file df.variable1.apply(np.round) # Turn column's values from str to int - Not mandatory (depends on variable type) # Replace variable1 by the name of a variable of source file df.variable1 = pd.to_numeric(df.variable1) # Get the maximum value of the variable and add 10% maxValueX = df.variable1.max() maxValueY = df.variable2.max() # Draw median (median values have beeen calculated externally) - Not mandatory plt.axvline(56, color='r') plt.axhline(93, color='r') plt.plot(df.variable1, df.variable2, 'ro', c='black') plt.axis([0, maxValueX, 0, maxValueY]) plt.xlabel('Variable1') plt.ylabel('Variable2') plt.show()
fb019f1130239371507b68417f1dc8403bbbde46
SwetaAsthana20/ProgrammingPractice
/LeetCode/Easy Module/LinkedList/PalindromeLinkList.py
1,482
3.90625
4
from LinkedListPack.LinkedList import LinkList def get_mid(slow_pointer, fast_pointer): while fast_pointer.next: slow_pointer = slow_pointer.next if not fast_pointer.next.next: break fast_pointer = fast_pointer.next.next return slow_pointer.next def reverse(head): if head and head.next: first_pointer = head second_pointer = head.next first_pointer.next = None while second_pointer.next: third_pointer = second_pointer.next second_pointer.next = first_pointer first_pointer = second_pointer second_pointer = third_pointer second_pointer.next = first_pointer return second_pointer else: return head def compare(first_pointer, second_pointer): while second_pointer: if first_pointer.value != second_pointer.value: return False first_pointer = first_pointer.next second_pointer = second_pointer.next return True def isPalindrome(head: LinkList) -> bool: if not head or not head.next: return True slow_pointer = head fast_pointer = head.next slow_pointer = get_mid(slow_pointer, fast_pointer) slow_pointer = reverse(slow_pointer) return compare(head, slow_pointer) ll = LinkList(20) ll.next = LinkList(50) ll.next.next = LinkList(10) ll.next.next.next = LinkList(50) ll.next.next.next.next = LinkList(0) a = isPalindrome(ll) print(a)
53fa7d727b412a98b6f6e755e0ba212f26d6e8e2
huynhminhtruong/py
/cp/atcoder/abc_136.py
1,689
3.5
4
import math import os import random import re import sys def sum_numbers(n): res = math.ceil(math.log(n, 10)) s = 1 if math.log(n, 10) % 2 == 0 else 0 for i in range(0, res, 2): k = 10**(i + 1) - 1 if n > k: s = s + 9 * (10 ** i) else: s = s + n - 10**i + 1 return s def check_non_decreasing_squares(n: int, a: list): p = a[0] for i in range(1, n): if a[i] > p: p = a[i] if p - a[i] == 1 or p - a[i] == 0: continue print("No") exit(0) print("Yes") def cal_distance_numbers(): k, x = list(map(int, input().rstrip().split())) for i in range(x - k + 1, x + k): print(i, end = " ") def count_anagram_strings(): n = int(input()) count = 0 d = dict() for i in range(n): key = "".join(sorted(list(input()))) if key not in d: d[key] = 1 else: d[key] += 1 # N numbers have N * (N - 1) / 2 pairs for v in d.values(): count += v * (v - 1) / 2 print(int(count)) if __name__ == '__main__': n, m = list(map(int, input().rstrip().split())) a, b = [0]*n, [0 for i in range(n)] for i in range(n): a[i], b[i] = list(map(int, input().rstrip().split())) # max days M so max of completed jobs is M # completed days should be less than M h, max_jobs, tmp, p, k = 0, 0, 0, 0, 0 while (p < n): while (k < n and m > 0): if a[k] <= m: tmp += b[k] m -= 1 k += 1 max_jobs = tmp if tmp > max_jobs else max_jobs tmp -= b[p] p += 1 m += 1
12f656bfd1568790f7def2887b527713902fd3e1
joeljoshy/Project
/Collections/Dictionary/Dictionary.py
818
4.3125
4
# Dictionary # Denoted by # dic = {} # Values stored in dictionary by key:value pairs dic = {'name': 'joel', 'Age': 23, 'Height': 6.1, 'Loc': 'EKM'} print(dic) # Supports heterogeneous data # Insertion order is preserved # Duplicate keys not supported # It supports duplicate values # Value can be collected from dictionary using its corresponding key # -------------------------------------------------------------------- # print(dic["name"]) # print(dic["Loc"]) # for i in dic: # print(i, ":", dic[i]) # It is mutable # --------------- # dic['Age']=22 # dic['Age']-=1 # print(dic) # REMOVING ELEMENTS # -------------------- # del dic['Height'] # print(dic) # dic.pop('Loc') # print(dic) # check key present in dictionary or not # print("age" in dic) dic['Gender'] = 'M' print(dic)
0211f2c2acc3bfd06a7ec9ffe0aa0a1f9bde7af1
weirdkhar/spindrift
/Instruments/gui_plot.py
11,176
3.671875
4
''' AnnotateablePlot Draw and interact with an annotateable plot Author: Kristina Johnson ''' import numpy as np import tkinter as tk import matplotlib.pyplot as plt import matplotlib.patches as mpatches from datetime import datetime as dt import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg class AnnotateablePlot(): ''' Draw a Plot that can be annotated ''' def __init__(self, tk_frame, timestamp, cols, names): # temporary data self.timestamp = timestamp self.columns = cols self.names = names # event coordinates self.x1 = None self.y1 = None self.x2 = None self.y2 = None self.coords = [] # list of selected points self.annotated = [] # list of annotated points self.annotation_mode = False # annotation mode added to avoid mouse event # conflict with the Matplotlib canvas # navigation tools # plot variables self.width = 2 self.fig1 = plt.figure(figsize=(13, 11), dpi=100) # Figure(figsize=(13, 11), dpi=100) self.ax = self.fig1.add_subplot(1, 1, 1) # plots self.plot_list = [] self.patch_list = [] # for the plot legend self.plot_selected = '' # create axis labels & legend self.ax.set_ylabel('Number', color="#555555", fontsize=12) self.ax.set_xlabel('TimeStamp', color="#555555", fontsize=12) # dynamic plot colours based on data self.colour_map = plt.get_cmap('viridis') linear_space = np.linspace(0, 1, len(self.columns)) self.colours = self.colour_map(linear_space) for i in range(0, len(self.columns)): self.plot_list.append(self.ax.plot(self.timestamp, self.columns[i], color=self.colours[i], linestyle='None', marker='o', markersize=2, picker=3)) self.patch_list.append(mpatches.Patch(color=self.colours[i], label=self.names[i])) self.ax.legend(handles=self.patch_list) canvas = FigureCanvasTkAgg(self.fig1, tk_frame) canvas.show() canvas.get_tk_widget().grid(row=1, column=0, columnspan=20, rowspan=20, sticky=(tk.NSEW), padx=5, pady=5) # navigation toolbar self.ccn_f41 = tk.LabelFrame(tk_frame, text='Navigation Tools') self.ccn_f41.grid(row=2, column=0, rowspan=1, columnspan=1, sticky=(tk.SW), padx=5) self.toolbar = NavigationToolbar2TkAgg(canvas, self.ccn_f41) self.toolbar.update() canvas._tkcanvas.grid(row=2, column=0, rowspan=1, columnspan=2, padx=5, pady=5) # event callbacks self.click = self.fig1.canvas.mpl_connect('pick_event', self.on_click) self.press = self.fig1.canvas.mpl_connect('button_press_event', self.on_press) self.drag = self.fig1.canvas.mpl_connect('button_release_event', self.on_release) self.key_press = self.fig1.canvas.mpl_connect('key_press_event', self.on_key_press) self.key_release = self.fig1.canvas.mpl_connect('key_release_event', self.on_key_release) # disconnect things later # self.fig1.canvas.mpl_disconnect(self.click) def compare_times(t_min, t_new, t_max): ''' Test if a time stamp is between a minimum and a maximum time. ''' t1 = dt.strptime(t_min, '%Y-%m-%d %H:%M:%S') t2 = dt.strptime(t_new, '%Y-%m-%d %H:%M:%S') t3 = dt.strptime(t_max, '%Y-%m-%d %H:%M:%S') if (t1 <= t2 <= t3): return True else: return False def is_in_array(self, point, array): ''' Test if a point is in the given array of data. Note: the on_click event counts from array 0 not 1. ''' int_x = int(point['x']) int_y = int(point['y']) if array[int_x - 1] == int_y: return True else: return False def is_in_rectangle(self, array): ''' Test to find points in array that are contained within the dragged rectangular selection. ''' x_min = None x_max = None y_min = None y_max = None if self.x2 > self.x1: x_min = self.x1 x_max = self.x2 else: x_min = self.x2 x_max = self.x1 if self.y2 > self.y1: y_min = self.y1 y_max = self.y2 else: y_min = self.y2 y_max = self.y1 for i in range(len(array)): print('Checking time stamps in is_in_rectangle') result = self.compare_times(x_min, self.timestamp[i], x_max) print('result=', result) if result and (y_min <= array[i] <= y_max): point = {'x': self.timestamp[i], 'y' : array[i]} print('point in rectangle = ', point) self.coords.append(point) def on_key_press(self, event): ''' Detect key presses. Activate annotation mode. ''' print('key_press:', event.key) if event.key == 'a': self.annotation_mode = True def on_key_release(self, event): ''' Detect key releases. Exit annotation mode. ''' print('key_release:', event.key) if event.key == 'a': self.annotation_mode = False def on_click(self, event): ''' Get the values of the chosen point in the scatterplot. ''' if self.annotation_mode == True: self.x1 = event.mouseevent.xdata self.y1 = event.mouseevent.ydata index = event.ind marker = event.artist x = np.take(marker.get_xdata(), index) y = np.take(marker.get_ydata(), index) point = {'x': x[0], 'y' : y[0]} print('point on_click = ', point) for i in range(0, len(self.columns)): if self.is_in_array(point, self.columns[i]): print('the point ', point, ' is in array', i+1) self.coords.append(point) self.annotate_this() self.annotation_mode = False def on_press(self, event): ''' Get the starting mouse coordinates of a rectangular selection. ''' if self.annotation_mode == True: self.x1 = event.xdata self.y1 = event.ydata print('on_press') def on_release(self, event): ''' Get the ending mouse coordinates of a rectangular selection. ''' if self.annotation_mode == True: self.x2 = event.xdata self.y2 = event.ydata print('on_release') print('x equals', self.x2, self.x1) print('y equals', self.y2, self.y1) # Check that this is not a single clicked point. # Do stuff for a dragged rectangular selection. if self.x1 != self.x2 or self.y1 != self.y2: for i in range(0, len(self.columns)): self.is_in_rectangle(self.columns[i]) if len(self.coords) > 0: self.annotate_this() self.annotation_mode = False def colouring_in(self): ''' Colour in the points that have been annotated ''' x_coords = [] y_coords = [] for i in range(len(self.annotated)): x_coords.append(self.annotated[i]['x']) y_coords.append(self.annotated[i]['y']) # Clear away previous plot. Otherwise they just accumulate. self.fig1.clf() # Redraw original plots. for i in range(0, len(self.columns)): self.plot_list.append(plt.plot(self.timestamp, self.columns[i], color=self.colours[i], linestyle='None', marker='o', markersize=2, picker=3)) # Create an additional plot which contains all of the annotated points. # This is overlaid on the original plots. # This is an inefficient way to accomplish the task, but the only one I could find that works. self.plot_selected = plt.plot(x_coords, y_coords, color='#ff1654', linestyle='None', marker='o', markersize=2, picker=3) # plot overlay self.fig1.canvas.draw() # redraw the canvas with plot overlay def annotate_this(self): ''' Pop-up window for annotation management. Currently, the user could create more than one of these. Future fix. ''' popup = tk.Tk() popup.wm_title('Annotation') text_box = tk.Text(popup, width=60, height=20) btn_add = tk.Button(popup, text='Add', command=lambda: self.add_annotation(text_box.get('0.0', 'end-1c'))) btn_remove = tk.Button(popup, text='Remove', command=lambda: self.remove_annotation(text_box.delete('1.0', tk.END))) btn_cancel = tk.Button(popup, text='Close Window', command=popup.destroy) # If the selected points are already annotated, display the annotations. if len(self.annotated) > 0: annotation_text = self.get_annotations() text_box.insert(tk.END, annotation_text) # draw the gui components text_box.grid(row=0, column=0, rowspan=1, columnspan=3, sticky=tk.NSEW, padx=5, pady=5) btn_add.grid(row=1, column=0, rowspan=1, columnspan=1, sticky=tk.E, padx=5, pady=5) btn_remove.grid(row=1, column=1, rowspan=1, columnspan=1, sticky=tk.E, padx=5, pady=5) btn_cancel.grid(row=1, column=2, rowspan=1, columnspan=1, sticky=tk.E, padx=5, pady=5) popup.mainloop() def add_annotation(self, text): ''' Add annotated things to a separate list. Clear the list of currently selected coordinates.''' self.annotated.extend(self.coords) for i in range(len(self.annotated)): if 'annotation' not in self.annotated[i]: self.annotated[i]['annotation'] = text print('annotated coordinates = ', self.annotated) self.colouring_in() self.coords = [] def remove_annotation(self, text): ''' Remove annotation from selected points.''' for i in range(len(self.coords)): for j in range(len(self.annotated)): if (self.coords[i]['x'] == self.annotated[j]['x']) and (self.coords[i]['y'] == self.annotated[j]['y']): print('self.annotated[j]: ', self.annotated[j]) print('self.coords[i]: ', self.coords[i]) del self.annotated[j] break self.colouring_in() self.coords = [] def get_annotations(self): ''' Get existing annotations for selected points.''' string = '' for i in range(len(self.coords)): for j in range(len(self.annotated)): if (self.coords[i]['x'] == self.annotated[j]['x']) and (self.coords[i]['y'] == self.annotated[j]['y']): x = 'x:' + str(self.annotated[j]['x']) y = 'y:' + str(self.annotated[j]['y']) string = string + x + ' ' + y + ' - ' + self.annotated[j]['annotation'] + '\n' return string
4a2dddcee84a7525c6ba2352d52170c2a60ebff4
sol20-meet/sub2p
/Labs_1-7/Lab_6/Lab_6.py
628
3.921875
4
from turtle import * import random import turtle import math class Ball(Turtle): def __init__(self,radius , color , speed): Turtle.__init__(self) self.shape("circle") self.shapesize(radius/10) self.radius = radius self.color(color) self.speed(speed) ball1 = Ball(50 , "red" , 50) ball2 = Ball(50 , "green" , 70) ball2.penup() ball2.goto(69,69) def Check_Collisions(ball1 , ball2): d = math.sqrt(math.pow(ball1.xcor() - ball2.xcor() , 2) + math.pow(ball1.ycor() - ball2.ycor() , 2)) r1 = ball1.radius r2 = ball2.radius if r1 + r2 >= d : print("Collisions") Check_Collisions(ball1 , ball2) turtle.mainloop()
82d47b1d2f42d30c9e56f632869b0c475527c85d
imcglo12/Dungeons-and-Monsters
/FirstMenu.py
457
3.953125
4
#This function will display the initial menu options #Imports import MenuSelection as ms #The function def main_menu(): count_1 = 10 while count_1 > 0: option_1 = input("\n\n Please choose an option below\n\n"\ " 1) Create New Character\n"\ " 2) Continue Game\n\n"\ " >>> ") count_1 = ms.check_2(option_1, count_1) return option_1
0180e17b6ac705379c8733fc76b763c1d4133afa
melfm/coding-interview-arena
/code/python/maths_questions.py
10,891
4.1875
4
#!/bin/python3 """Maths & Probability Questions.""" import math import numpy as np import sys def divisible_by_r(m, n): """Q: Given two numbers m and n, write a method to return the first number r that is divisible by both - > Least common multiple """ def gcd(m, n): if n == 0: return m else: return gcd(n, m % n) return m * n / gcd(m, n) def generate_rand_7(): """Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5 (i.e., implement rand7() using rand5()). Solution based on accept-reject algorithm. """ while (True): # This generates a random number uniformly distributed between 1 and 24. # The first term is 5 times a rand num between 1 - 4, yielding {5, 10, # 15, 20}. The second is a rand num between 1 - 4. # Since the two numbers are *independent*, adding them gives a rand num # uniformly distributed between 1 - 24. # The test then rejects any number that is 21 or above. This is then # divided into 7 numbers between 1 - 7 using % 7. Since there are 21 # numbers in the interval [1, 21] and 21 is divisble by 7, the numbers # between 1 and 7 will occur with equal probability. num = 5 * (np.random.uniform(1, 5, 1) - 1) +\ (np.random.uniform(1, 5, 1) - 1) if num[0] < 21: return int(num[0] % 7 + 1) def sample_distribution(numbers, probabilities, num_samples): """Given a list of numbers and corresponding probabilities, sample 'num_samples' numbers. Note that the probabilities sum to 1. """ intervals = [] intervals.append(probabilities[0]) new_interval = probabilities[0] for i in range(1, len(probabilities)): new_interval += probabilities[i] intervals.append(new_interval) counter = 0 new_numbers = [] while counter <= num_samples: for i in range(len(intervals)): # Generate a random num between 0 - 1 # i.e. flip a coin. rand_prob = np.random.random_sample((1, )) if rand_prob <= [intervals[i]]: new_numbers.append(numbers[i]) counter += 1 return new_numbers def factorial_trailing_zero(n): """Given an integer n, return the number of trailing zeroes in n!. A simple method is to first calculate factorial of n, then count trailing 0s in the result. But this can cause overflow for a big numbers as the factorial becomes large. Instead consider prime factors, a trailing zero is produced by 2 and 5. It turns out the number of 2s in prime factors is always more than or equal to the number of 5s, so we just need to count 5s. Finally, we also need to consider numbers like 25, 125 etc that have more than one 5 (consider 28!). To handle this, we start by dividing by 5, and then multiples of 5, like 25 and so on. The formula becomes: floor(n/5) + floor(n/25) + floor(n/125) .... """ count = 0 idx = 5 while (n / idx >= 1): count += math.floor(n / idx) idx *= 5 return count def closest_palindrome_number(number): """Given a number, find the closest Palindrome number whose absolute difference with given number is minimum and absolute difference must be greater than 0. Input: 121 Output: [131, 111] Input: 1234 Outpyt: 1221 The trick here to mirror the first half of the digit onto the second half. Turns out this will always give you the shortest distane you need to the number, and obviously we would not want to mirror the second half for this reason. Once we mirror, say 121 stays 121, then out next options are adding and subtracting one from this middle number to get 111 and 131. We can then check for min distance. """ def check_all_9(number): for n in number: if n != 9: return False return True num_list = [int(i) for i in str(number)] num_size = len(num_list) if check_all_9(num_list): return number + 2 mid_point = int(num_size / 2) def list_to_int(nums): return int(''.join(str(i) for i in nums)) def check_palindromes(all_palindromes, number): min_found = sys.maxsize pal_found = 0 multiple_pals = [] for i in all_palindromes: pal = list_to_int(i) distance = abs(number - pal) if distance <= min_found and distance != 0: if distance == min_found: multiple_pals.append(i) else: multiple_pals = [] min_found = distance pal_found = i multiple_pals.append(i) if len(multiple_pals) == 1: return list_to_int(pal_found) else: numbers = [] for i in multiple_pals: number = list_to_int(i) numbers.append(number) return numbers if num_size % 2 == 0: # Even number splitted = num_list[0:mid_point] mirrored = splitted + splitted[::-1] all_palindromes = [] all_palindromes.append(mirrored) if splitted[-1] != 9: split_add_one = list(splitted) split_add_one[-1] += 1 split_add_one = all_palindromes.append(split_add_one + split_add_one[::-1]) if splitted[-1] != 0: split_sub_one = list(splitted) split_sub_one[-1] -= 1 split_sub_one = all_palindromes.append(split_sub_one + split_sub_one[::-1]) else: # Odd number splitted = num_list[0:mid_point] middle_num = num_list[mid_point] all_palindromes = [] all_palindromes.append(splitted + [middle_num] + splitted[::-1]) if middle_num != 9: all_palindromes.append(splitted + [middle_num + 1] + splitted[::-1]) if middle_num != 0: all_palindromes.append(splitted + [middle_num - 1] + splitted[::-1]) return check_palindromes(all_palindromes, number) """Orientation of 3 ordered points. Orientation of an ordered triplet of points in the plane can be - counterclockwise - clockwise - collinear """ class Point: def __init__(self, x, y): self.x = x self.y = y def print_coord(self): print('[', self.x, ',', self.y, ']') def orientation3ps(p1, p2, p3): # Returns the following values: # 0 : Collinear points # 1 : Clockwise points # 2 : Counterclockwise # This is done based on a formula comparing the slope # angles between points val = (float(p2.y - p1.y) * (p3.x - p2.x)) - \ (float(p2.x - p1.x) * (p3.y - p2.y)) if (val > 0): # Clockwise orientation return 1 elif (val < 0): # Counterclockwise orientation return 2 else: # Collinear orientation return 0 """ Convex Hull Question. Given a set of points in the plane, the convex hull of the set is the smallest convex polygon that contains all the points of it. Jarvis's Algorithm or Wrapping. Step 1) Initialize p as leftmost point. Step 2) The next point q is the point such that the triplet (p, q, r) is counterclockwise for any other point r. To find this initialize q as next point, traverse thru all the points. For any point i, if its more counterclockwise i.e. orientation(p, i, q) is counterclockwise then update q as i. Final value of q is going to be the most counterclockwise point. """ def left_index(points): min_p = 0 for i in range(len(points)): point = points[i] if point.x < points[min_p].x: min_p = i elif point.x == points[min_p].x: # now check Y if point.y < points[min_p].y: min_p = i return min_p def convex_hull(points, n): # Need at least 3 points if n < 3: return left_p = left_index(points) convex_hull_ps = [] # Start from leftmost keep moving counterclockwise. p = left_p q = 0 while (True): convex_hull_ps.append(p) # Keep track of last visited most counterclockwise # mod n stops it from going outside of bound of set q = (p + 1) % n for i in range(n): if (orientation3ps(points[p], points[i], points[q]) == 2): q = i # q is now the most counterclockwise, lets move on to the # next set of points p = q # Back to the first point if (p == left_p): break print('Convex hull points: ') for i in convex_hull_ps: print(points[i].x, points[i].y) def look_and_say(n): """ Implement a function that outputs the Look and Say sequence. 1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 """ # Base cases if (n == 1): return "1" if (n == 2): return "11" prev_term = "11" for i in range(3, n + 1): # Add a dummy character to allow extra iteration # without this, your very first loop will exit prev_term += '$' seq_end = len(prev_term) count = 1 seq_n = '' for j in range(1, seq_end): if (prev_term[j] != prev_term[j - 1]): seq_n += str(count) seq_n += prev_term[j - 1] count = 1 else: count += 1 print('\n LNS: ', seq_n) prev_term = seq_n print('\n') return prev_term def get_key_from_value(d, val): keys = [k for k, v in d.items() if v == val] if keys: return keys[0] return None def ice_cream_parlor(m, cost): cost_map = {} index_x = index_y = None for i in range(len(cost)): x = cost[i] y_sol = -x + m if y_sol in cost_map.values(): index_x = i index_y = get_key_from_value(cost_map, y_sol) output = [index_x, index_y] return output else: # If the solution doesn't already exist # check for multiples of y for any_y in cost_map.values(): if y_sol > 0 and y_sol % any_y == 0: index_x = i index_y = get_key_from_value(cost_map, any_y) output = [index_x, index_y] return output cost_map.update({i: x}) # Solution not found output = [index_x, index_y] return output
025c740813f7eea37abadaa14ffe0d8c1bedc79d
eric496/leetcode.py
/design/170.two_sum_III_data_structure_design.py
1,116
4.09375
4
""" Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value. Example 1: add(1); add(3); add(5); find(4) -> true find(7) -> false Example 2: add(3); add(1); add(2); find(3) -> true find(6) -> false """ class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.cnt = {} def add(self, number: int) -> None: """ Add the number to an internal data structure.. """ self.cnt[number] = self.cnt.get(number, 0) + 1 def find(self, value: int) -> bool: """ Find if there exists any pair of numbers which sum is equal to the value. """ for num in self.cnt: if value - num in self.cnt: if value - num == num: if self.cnt[num] > 1: return True else: return True return False
fd8c53ec55048c99cfa0a7a4da6cb565e7806458
paymog/ProjectEuler
/Problems 10-19/Problem14/BruteForce.py
693
3.59375
4
''' Created on Jan 18, 2013 @author: PaymahnMoghadasian ''' from test.test_iterlen import len found_values = {} def find_collatz_length(n): if n == 1: return 1 elif found_values.has_key(n): return found_values[n] else: if n % 2 == 0: return 1 + find_collatz_length(n / 2) else: return 1 + find_collatz_length(3 * n + 1) largest_seed = 0 largest_length = 0 for i in range(1, 1000000): length = find_collatz_length(i) found_values[i] = length # print i, " : ", length if(length > largest_length): largest_seed = i largest_length = length print largest_seed
d0c8dc2d64c55660b08e75b1132de1cf8a9bbe93
LSSTDESC/DC2-production
/scripts/stripe_visits.py
783
3.546875
4
#!/usr/bin/env python """ Take a list of visits and divided them up into num_files by striping through the visit list. E.g., a file with a list from 1-55 with num_files = 10 would get divided up as 1 11 21 31 41 51 2 12 22 32 42 52 3 13 23 33 43 53 4 14 24 34 44 54 5 15 25 55 45 55 6 16 26 66 46 7 17 27 77 47 8 18 28 88 48 9 19 29 99 49 10 20 30 40 50 """ import sys import os visit_file = sys.argv[1] num_files = int(sys.argv[2]) with open(visit_file, 'r') as f: visits = f.readlines() basename, ext = os.path.splitext(visit_file) lines_per_file = (len(visits) // num_files) + 1 for i in range(num_files): these_visits = visits[i::num_files] new_name = '{}_{}{}'.format(basename, i, ext) with open(new_name, 'w') as of: of.writelines(these_visits)
b59818c0a7f5f957fb2bbb1190410399f78e7d11
weichuntsai0217/work-note
/programming-interviews/epi-in-python/ch17/Greedy_algorithms_boot_camp.py
530
3.859375
4
from __future__ import print_function def get_min_num_coins_for_change(cents): """ Time complexity is O(1) """ coins = [100, 50, 25, 10, 5, 1] # american coins num_of_coins = 0 for coin in coins: num_of_coins += (cents / coin) cents %= coin return num_of_coins def get_input(hard=False): return 753, 7+1+3 def main(): for arg in [False]: cents, ans = get_input(arg) print('Test success' if get_min_num_coins_for_change(cents) == ans else 'Test failure') if __name__ == '__main__': main()
ef8f5431d0c0c23d7702482b5fd2160dfcd33641
m-blue/prg105-Ex-16.7-Date-Calculations
/Ex 16.7 Date Calculations.py
938
4.25
4
import datetime def your_age(today, birth): age = today.year - birth.year if birth.month > today.month: age += 1 elif birth.month == today.month: if birth.day >= today.day: age += 1 return age def days_until_birthday(today, birth): if birth.strftime('%j') > date.strftime('%j'): count = birth.strftime('%j') - today.strftime('%j') elif today.strftime('%j') > birth.strftime('%j'): count = (365 - int(today.strftime('%j')) )+ int(birth.strftime('%j')) else: count = 0 return count date = datetime.datetime.today() birthday = raw_input("Type in your birth date in {Month} {day}, {year} format (ex: January 1, 1999): ") format = '%B %d, %Y' birthday = datetime.datetime.strptime(birthday, format) print 'You are %d years old' % your_age(date,birthday) print 'Your birthday is in %s days' % days_until_birthday(date,birthday)
48fd06216c6aaf8ccb0ddc6ceca7fb3c142566eb
seahawkz/python_stack
/_python/OOP/user.py
1,162
3.703125
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 # deposit def make_deposit(self, amount): self.account_balance += amount # withdrawal def make_withdrawal(self, amount): self.account_balance -= amount # display user balance def display_user_balance(self): print(f"User: {self.name}, Balance: ${self.account_balance}") # transfer money def transfer_money(self, other_user, amount): other_user.make_deposit(amount) self.make_withdrawal(amount) fred = User("Fred", "fred@email.com") jen = User("Jen", "jen@email.com") john = User("John", "john@email.com") fred.make_deposit(200) fred.make_deposit(1450) fred.make_deposit(500) fred.make_withdrawal(325) fred.display_user_balance() jen.make_deposit(230) jen.make_deposit(380) jen.make_withdrawal(110) jen.make_withdrawal(234) jen.display_user_balance() john.make_deposit(1050) john.make_withdrawal(150) john.make_withdrawal(230) john.make_withdrawal(565) john.display_user_balance() fred.transfer_money(john, 300) fred.display_user_balance() john.display_user_balance()
b438aca0761f0efbd27083bbe5eee7e1646b6364
sleeperbus/coursera
/Algorithms/Part1/3_sum_brute_force.py
433
3.640625
4
class threeSum: def __init__(self, arr): self.data = arr self.count = 0 def occurance(self): for i in range(len(self.data)): for j in range(1, len(self.data)): for k in range(2, len(self.data)): if self.data[i] + self.data[j] + self.data[k] == 0: self.count = self.count + 1 return self.count testData = [30, -40, -20, -10, 40, 0, 10, 5] testThree = threeSum(testData) print testThree.occurance()
ec0a2543a3b520a40b4c3aae57d92a7a7bd0a512
tripathyA5/SD-Project
/sd1.py
470
3.671875
4
import csv import math with open('sdData.csv',newline='') as f: reader=csv.reader(f) fileData=list(reader) data = fileData[0] def mean(data): n = len(data) total = 0 for i in data: total=total+int(i) mean = total/n return mean squareList=[] for number in data: a = int(number)-mean(data) a = a*2 squareList.append(a) sum = 0 for i in squareList: sum=sum+i result = sum/(len(data)-1) sd = math.sqrt(result) print(sd)
3b9515786a9eb7f7d1ec73cd4edeeb4c4022d9c9
vdmitriv15/DZ_Lesson_1
/DZ_1.py
712
4.3125
4
# калькулятор отрабатывающий сложение, вычитание, умножение и деление number_1 = int(input("веедите число: ")) number_2 = int(input("веедите второе число: ")) action = input('действие ("+", "-", "*", "/"): ') if action == "+": result = number_1 + number_2 elif action == "-": result = number_1 - number_2 elif action == "*": result = number_1 * number_2 elif action == "/" and number_2 != 0: result = number_1 / number_2 elif action == "/" and number_2 == 0: print("Ошибка! Попытка деления на 0") else: print("Ошибка! Некоретное действие.")
6872c426fdcb319e7c70d68a86911a26f7a0372f
harrifeng/Python-Study
/Leetcode/Remove_Duplicates_from_Sorted_Array_II.py
596
3.984375
4
""" Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. """ class Solution: # @param A a list of integers # @return an integer def removeDuplicates(self, A): if len(A) <= 2: return len(A) start = 1 cur = 2 while cur < len(A): if A[cur] != A[start] or A[cur] != A[start-1]: A[start+1] = A[cur] start += 1 cur+= 1 return start+1
220b2bdfdba7a5b59b216155bfdf200fe2c97741
runnersaw/chessAI
/chess.py
52,291
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon May 5 20:23:59 2014 @author: sawyer """ import pygame from pygame.locals import * import sys import time import copy size = (600, 600) all_spaces = [] for i in range(1,9): for j in range(1,9): all_spaces.append((i,j)) class Piece(): def __init__(self, pos, team): self.pos = pos self.team = team self.alive = True self.moved = False def move(self, end_pos): self.pos = end_pos self.moved = True def check_valid_moves(self, moves): valid_moves = [] for move in moves: if move[0] in range(1,9) and move[1] in range(1,9): valid_moves.append(move) return valid_moves class Pawn(Piece): def __init__(self, pos, team): Piece.__init__(self, pos, team) self.score = 1 def valid_moves(self, pieces): moves = [] if self.team == 'Black': if (self.pos[0]+1, self.pos[1]) not in pieces.get_black_spaces(): if (self.pos[0]+1, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]+1, self.pos[1])) if self.pos[0] == 2: if (self.pos[0]+1, self.pos[1]) not in pieces.get_white_spaces(): if (self.pos[0]+2, self.pos[1]) not in pieces.get_black_spaces(): if (self.pos[0]+2, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]+2, self.pos[1])) if (self.pos[0]+1, self.pos[1]+1) in pieces.get_white_spaces(): moves.append((self.pos[0]+1, self.pos[1]+1)) if (self.pos[0]+1, self.pos[1]-1) in pieces.get_white_spaces(): moves.append((self.pos[0]+1, self.pos[1]-1)) self.check_valid_moves(moves) return moves if self.team == 'White': if (self.pos[0]-1, self.pos[1]) not in pieces.get_black_spaces(): if (self.pos[0]-1, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]-1, self.pos[1])) if self.pos[0] == 7: if (self.pos[0]-1, self.pos[1]) not in pieces.get_black_spaces(): if (self.pos[0]-2, self.pos[1]) not in pieces.get_white_spaces(): if (self.pos[0]-2, self.pos[1]) not in pieces.get_black_spaces(): moves.append((self.pos[0]-2, self.pos[1])) if (self.pos[0]-1, self.pos[1]+1) in pieces.get_black_spaces(): moves.append((self.pos[0]-1, self.pos[1]+1)) if (self.pos[0]-1, self.pos[1]-1) in pieces.get_black_spaces(): moves.append((self.pos[0]-1, self.pos[1]-1)) moves = self.check_valid_moves(moves) return moves class Rook(Piece): def __init__(self, pos, team): Piece.__init__(self, pos, team) self.score = 5 def valid_moves(self, pieces): moves = [] directions = ['right', 'left', 'up', 'down'] for direction in directions: if direction == 'right': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0], self.pos[1]+count) not in pieces.get_white_spaces(): moves.append((self.pos[0], self.pos[1]+count)) if (self.pos[0], self.pos[1]+count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0], self.pos[1]+count) not in pieces.get_black_spaces(): moves.append((self.pos[0], self.pos[1]+count)) if (self.pos[0], self.pos[1]+count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'left': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0], self.pos[1]-count) not in pieces.get_white_spaces(): moves.append((self.pos[0], self.pos[1]-count)) if (self.pos[0], self.pos[1]-count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0], self.pos[1]-count) not in pieces.get_black_spaces(): moves.append((self.pos[0], self.pos[1]-count)) if (self.pos[0], self.pos[1]-count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'up': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]-count, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]-count, self.pos[1])) if (self.pos[0]-count, self.pos[1]) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]-count, self.pos[1]) not in pieces.get_black_spaces(): moves.append((self.pos[0]-count, self.pos[1])) if (self.pos[0]-count, self.pos[1]) in pieces.get_white_spaces(): run = False else: run = False if direction == 'down': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]+count, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]+count, self.pos[1])) if (self.pos[0]+count, self.pos[1]) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]+count, self.pos[1]) not in pieces.get_black_spaces(): moves.append((self.pos[0]+count, self.pos[1])) if (self.pos[0]+count, self.pos[1]) in pieces.get_white_spaces(): run = False else: run = False moves = self.check_valid_moves(moves) return moves class Bishop(Piece): def __init__(self, pos, team): Piece.__init__(self, pos, team) self.score = 3 def valid_moves(self, pieces): moves = [] directions = ['right', 'left', 'up', 'down'] for direction in directions: if direction == 'right': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]+count, self.pos[1]+count) not in pieces.get_white_spaces(): moves.append((self.pos[0]+count, self.pos[1]+count)) if (self.pos[0]+count, self.pos[1]+count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]+count, self.pos[1]+count) not in pieces.get_black_spaces(): moves.append((self.pos[0]+count, self.pos[1]+count)) if (self.pos[0]+count, self.pos[1]+count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'left': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]+count, self.pos[1]-count) not in pieces.get_white_spaces(): moves.append((self.pos[0]+count, self.pos[1]-count)) if (self.pos[0]+count, self.pos[1]-count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]+count, self.pos[1]-count) not in pieces.get_black_spaces(): moves.append((self.pos[0]+count, self.pos[1]-count)) if (self.pos[0]+count, self.pos[1]-count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'up': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]-count, self.pos[1]+count) not in pieces.get_white_spaces(): moves.append((self.pos[0]-count, self.pos[1]+count)) if (self.pos[0]-count, self.pos[1]+count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]-count, self.pos[1]+count) not in pieces.get_black_spaces(): moves.append((self.pos[0]-count, self.pos[1]+count)) if (self.pos[0]-count, self.pos[1]+count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'down': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]-count, self.pos[1]-count) not in pieces.get_white_spaces(): moves.append((self.pos[0]-count, self.pos[1]-count)) if (self.pos[0]-count, self.pos[1]-count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]-count, self.pos[1]-count) not in pieces.get_black_spaces(): moves.append((self.pos[0]-count, self.pos[1]-count)) if (self.pos[0]-count, self.pos[1]-count) in pieces.get_white_spaces(): run = False else: run = False moves = self.check_valid_moves(moves) return moves class Knight(Piece): def __init__(self, pos, team): Piece.__init__(self, pos, team) self.score = 3 def valid_moves(self, pieces): moves = [] if self.team == 'White': if (self.pos[0]-2, self.pos[1]-1) not in pieces.get_white_spaces(): moves.append((self.pos[0]-2, self.pos[1]-1)) if self.team == 'White': if (self.pos[0]-2, self.pos[1]+1) not in pieces.get_white_spaces(): moves.append((self.pos[0]-2, self.pos[1]+1)) if self.team == 'White': if (self.pos[0]-1, self.pos[1]-2) not in pieces.get_white_spaces(): moves.append((self.pos[0]-1, self.pos[1]-2)) if self.team == 'White': if (self.pos[0]-1, self.pos[1]+2) not in pieces.get_white_spaces(): moves.append((self.pos[0]-1, self.pos[1]+2)) if self.team == 'White': if (self.pos[0]+1, self.pos[1]-2) not in pieces.get_white_spaces(): moves.append((self.pos[0]+1, self.pos[1]-2)) if self.team == 'White': if (self.pos[0]+1, self.pos[1]+2) not in pieces.get_white_spaces(): moves.append((self.pos[0]+1, self.pos[1]+2)) if self.team == 'White': if (self.pos[0]+2, self.pos[1]-1) not in pieces.get_white_spaces(): moves.append((self.pos[0]+2, self.pos[1]-1)) if self.team == 'White': if (self.pos[0]+2, self.pos[1]+1) not in pieces.get_white_spaces(): moves.append((self.pos[0]+2, self.pos[1]+1)) if self.team == 'Black': if (self.pos[0]-2, self.pos[1]-1) not in pieces.get_black_spaces(): moves.append((self.pos[0]-2, self.pos[1]-1)) if self.team == 'Black': if (self.pos[0]-2, self.pos[1]+1) not in pieces.get_black_spaces(): moves.append((self.pos[0]-2, self.pos[1]+1)) if self.team == 'Black': if (self.pos[0]-1, self.pos[1]-2) not in pieces.get_black_spaces(): moves.append((self.pos[0]-1, self.pos[1]-2)) if self.team == 'Black': if (self.pos[0]-1, self.pos[1]+2) not in pieces.get_black_spaces(): moves.append((self.pos[0]-1, self.pos[1]+2)) if self.team == 'Black': if (self.pos[0]+1, self.pos[1]-2) not in pieces.get_black_spaces(): moves.append((self.pos[0]+1, self.pos[1]-2)) if self.team == 'Black': if (self.pos[0]+1, self.pos[1]+2) not in pieces.get_black_spaces(): moves.append((self.pos[0]+1, self.pos[1]+2)) if self.team == 'Black': if (self.pos[0]+2, self.pos[1]-1) not in pieces.get_black_spaces(): moves.append((self.pos[0]+2, self.pos[1]-1)) if self.team == 'Black': if (self.pos[0]+2, self.pos[1]+1) not in pieces.get_black_spaces(): moves.append((self.pos[0]+2, self.pos[1]+1)) moves = self.check_valid_moves(moves) return moves class King(Piece): def __init__(self, pos, team): Piece.__init__(self, pos, team) self.score = 0 def valid_moves(self, pieces): moves = [] space = (self.pos[0]+1, self.pos[1]+1) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0]+1, self.pos[1]) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0]+1, self.pos[1]-1) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0], self.pos[1]+1) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0], self.pos[1]-1) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0]-1, self.pos[1]+1) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0]-1, self.pos[1]) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) space = (self.pos[0]-1, self.pos[1]-1) if self.team == 'White': if space not in pieces.get_threatened_by_black() and space not in pieces.get_white_spaces(): moves.append(space) if self.team == 'Black': if space not in pieces.get_threatened_by_white() and space not in pieces.get_black_spaces(): moves.append(space) moves = self.check_valid_moves(moves) return moves class Queen(Piece): def __init__(self, pos, team): Piece.__init__(self, pos, team) self.score = 9 def valid_moves(self, pieces): moves = [] directions = ['right', 'left', 'up', 'down'] for direction in directions: if direction == 'right': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]+count, self.pos[1]+count) not in pieces.get_white_spaces(): moves.append((self.pos[0]+count, self.pos[1]+count)) if (self.pos[0]+count, self.pos[1]+count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]+count, self.pos[1]+count) not in pieces.get_black_spaces(): moves.append((self.pos[0]+count, self.pos[1]+count)) if (self.pos[0]+count, self.pos[1]+count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'left': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]+count, self.pos[1]-count) not in pieces.get_white_spaces(): moves.append((self.pos[0]+count, self.pos[1]-count)) if (self.pos[0]+count, self.pos[1]-count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]+count, self.pos[1]-count) not in pieces.get_black_spaces(): moves.append((self.pos[0]+count, self.pos[1]-count)) if (self.pos[0]+count, self.pos[1]-count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'up': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]-count, self.pos[1]+count) not in pieces.get_white_spaces(): moves.append((self.pos[0]-count, self.pos[1]+count)) if (self.pos[0]-count, self.pos[1]+count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]-count, self.pos[1]+count) not in pieces.get_black_spaces(): moves.append((self.pos[0]-count, self.pos[1]+count)) if (self.pos[0]-count, self.pos[1]+count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'down': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]-count, self.pos[1]-count) not in pieces.get_white_spaces(): moves.append((self.pos[0]-count, self.pos[1]-count)) if (self.pos[0]-count, self.pos[1]-count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]-count, self.pos[1]-count) not in pieces.get_black_spaces(): moves.append((self.pos[0]-count, self.pos[1]-count)) if (self.pos[0]-count, self.pos[1]-count) in pieces.get_white_spaces(): run = False else: run = False directions = ['right', 'left', 'up', 'down'] for direction in directions: if direction == 'right': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0], self.pos[1]+count) not in pieces.get_white_spaces(): moves.append((self.pos[0], self.pos[1]+count)) if (self.pos[0], self.pos[1]+count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0], self.pos[1]+count) not in pieces.get_black_spaces(): moves.append((self.pos[0], self.pos[1]+count)) if (self.pos[0], self.pos[1]+count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'left': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0], self.pos[1]-count) not in pieces.get_white_spaces(): moves.append((self.pos[0], self.pos[1]-count)) if (self.pos[0], self.pos[1]-count) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0], self.pos[1]-count) not in pieces.get_black_spaces(): moves.append((self.pos[0], self.pos[1]-count)) if (self.pos[0], self.pos[1]-count) in pieces.get_white_spaces(): run = False else: run = False if direction == 'up': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]-count, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]-count, self.pos[1])) if (self.pos[0]-count, self.pos[1]) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]-count, self.pos[1]) not in pieces.get_black_spaces(): moves.append((self.pos[0]-count, self.pos[1])) if (self.pos[0]-count, self.pos[1]) in pieces.get_white_spaces(): run = False else: run = False if direction == 'down': run = True count = 0 while run: count+=1 if count>8: run = False if self.team == 'White': if (self.pos[0]+count, self.pos[1]) not in pieces.get_white_spaces(): moves.append((self.pos[0]+count, self.pos[1])) if (self.pos[0]+count, self.pos[1]) in pieces.get_black_spaces(): run = False else: run = False if self.team == 'Black': if (self.pos[0]+count, self.pos[1]) not in pieces.get_black_spaces(): moves.append((self.pos[0]+count, self.pos[1])) if (self.pos[0]+count, self.pos[1]) in pieces.get_white_spaces(): run = False else: run = False moves = self.check_valid_moves(moves) return moves class Pieces: def __init__(self): self.wp1 = Pawn((7,1), 'White') self.wp2 = Pawn((7,2), 'White') self.wp3 = Pawn((7,3), 'White') self.wp4 = Pawn((7,4), 'White') self.wp5 = Pawn((7,5), 'White') self.wp6 = Pawn((7,6), 'White') self.wp7 = Pawn((7,7), 'White') self.wp8 = Pawn((7,8), 'White') self.wr1 = Rook((8,1), 'White') self.wk1 = Knight((8,2), 'White') self.wb1 = Bishop((8,3), 'White') self.wq = Queen((8,4), 'White') self.wk = King((8,5), 'White') self.wb2 = Bishop((8,6), 'White') self.wk2 = Knight((8,7), 'White') self.wr2 = Rook((8,8), 'White') self.bp1 = Pawn((2,1), 'Black') self.bp2 = Pawn((2,2), 'Black') self.bp3 = Pawn((2,3), 'Black') self.bp4 = Pawn((2,4), 'Black') self.bp5 = Pawn((2,5), 'Black') self.bp6 = Pawn((2,6), 'Black') self.bp7 = Pawn((2,7), 'Black') self.bp8 = Pawn((2,8), 'Black') self.br1 = Rook((1,1), 'Black') self.bk1 = Knight((1,2), 'Black') self.bb1 = Bishop((1,3), 'Black') self.bq= Queen((1,4), 'Black') self.bk = King((1,5), 'Black') self.bb2 = Bishop((1,6), 'Black') self.bk2 = Knight((1,7), 'Black') self.br2 = Rook((1,8), 'Black') self.pieces = [self.wp1, self.wp2, self.wp3, self.wp4, self.wp5, self.wp6, self.wp7, self.wp8, self.wr1, self.wb1, self.wk1, self.wk, self.wq, self.wb2, self.wk2, self.wr2, self.bp1, self.bp2, self.bp3, self.bp4, self.bp5, self.bp6, self.bp7, self.bp8, self.br1, self.bk1, self.bb1, self.bq, self.bk, self.bb2, self.bk2, self.br2] self.black_pieces = [self.bp1, self.bp2, self.bp3, self.bp4, self.bp5, self.bp6, self.bp7, self.bp8, self.br1, self.bk1, self.bb1, self.bq, self.bk, self.bb2, self.bk2, self.br2] self.white_pieces = [self.wp1, self.wp2, self.wp3, self.wp4, self.wp5, self.wp6, self.wp7, self.wp8, self.wr1, self.wb1, self.wk1, self.wk, self.wq, self.wb2, self.wk2, self.wr2] def return_board_state(self): output = {} def check_valid_moves(self, moves): valid_moves = [] for move in moves: if move[0] in range(1,9) and move[1] in range(1,9): valid_moves.append(move) return valid_moves def all_moves(self): output = {} for piece in self.pieces: output[piece.pos] = piece.valid_moves(self) return output def all_team_moves(self, team): output = {} for piece in self.pieces: if piece.team == team: if piece.valid_moves(self) != []: output[piece.pos] = piece.valid_moves(self) return output def get_white_spaces(self): spaces = [] for piece in self.pieces: if piece.team == 'White': spaces.append(piece.pos) return spaces def get_black_spaces(self): spaces = [] for piece in self.pieces: if piece.team == 'Black': spaces.append(piece.pos) return spaces def get_threatened_by_black(self): spaces = [] for piece in self.black_pieces: if not isinstance(piece, King): spaces.extend(piece.valid_moves(self)) else: space = (piece.pos[0]+1, piece.pos[1]+1) spaces.extend([space]) space = (piece.pos[0]+1, piece.pos[1]) spaces.extend([space]) space = (piece.pos[0]+1, piece.pos[1]-1) spaces.extend([space]) space = (piece.pos[0], piece.pos[1]+1) spaces.extend([space]) space = (piece.pos[0], piece.pos[1]-1) spaces.extend([space]) space = (piece.pos[0]-1, piece.pos[1]+1) spaces.extend([space]) space = (piece.pos[0]-1, piece.pos[1]) spaces.extend([space]) space = (piece.pos[0]-1, piece.pos[1]-1) spaces.extend([space]) spaces = self.check_valid_moves(spaces) return spaces def get_threatened_by_white(self): spaces = [] for piece in self.white_pieces: if not isinstance(piece, King): spaces.extend(piece.valid_moves(self)) else: space = (piece.pos[0]+1, piece.pos[1]+1) spaces.extend([space]) space = (piece.pos[0]+1, piece.pos[1]) spaces.extend([space]) space = (piece.pos[0]+1, piece.pos[1]-1) spaces.extend([space]) space = (piece.pos[0], piece.pos[1]+1) spaces.extend([space]) space = (piece.pos[0], piece.pos[1]-1) spaces.extend([space]) space = (piece.pos[0]-1, piece.pos[1]+1) spaces.extend([space]) space = (piece.pos[0]-1, piece.pos[1]) spaces.extend([space]) space = (piece.pos[0]-1, piece.pos[1]-1) spaces.extend([space]) spaces = self.check_valid_moves(spaces) return spaces def get_piece_from_position(self, space): for piece in self.pieces: if piece.pos == space: return piece return None def move(self, piece, space): piece_to_delete = self.get_piece_from_position(space) if piece_to_delete != None: self.delete_piece(space) piece.move(space) def delete_piece(self, space): piece_to_delete = self.get_piece_from_position(space) for piece in self.pieces: if piece_to_delete == piece: self.pieces.remove(piece) if piece_to_delete.team == 'White': self.white_pieces.remove(piece) if piece_to_delete.team == 'Black': self.black_pieces.remove(piece) del piece def find_orig_space_and_new_space(self, pieces_class): for piece in self.pieces: other_piece = pieces_class.get_piece_from_position(piece.pos) if type(piece) != type(other_piece): orig_space = piece.pos for piece in pieces_class.pieces: other_piece = self.get_piece_from_position(piece.pos) if type(piece) != type(other_piece) or piece.team != other_piece.team: new_space = piece.pos return [orig_space, new_space] class AI: def __init__(self, team, model): self.team = team self.model = model def change_team(self, team): if team == 'White': return 'Black' return 'White' def check_board_state(self, model_class): own_score = 0 opponent_score = 0 opponent_team = self.change_team(self.team) for piece in model_class.pieces.pieces: if piece.team == self.team: own_score += piece.score else: opponent_score += piece.score if model_class.check_win(self.team): return 100000 elif model_class.check_win(opponent_team): return -100000 else: return own_score/float(opponent_score) def make_child_model(self, model_class, piece, space): model = copy.deepcopy(model_class) new_piece = model.pieces.get_piece_from_position(piece.pos) model.pieces.move(new_piece, space) model.change_turn() return model def make_all_child_nodes(self, model): output = [] for piece in model.all_valid_moves: if piece.team == model.turn: for space in model.all_valid_moves[piece]: output.append(self.make_child_model(model, piece, space)) return output def return_all_child_nodes_scores(self, model): output = [] list_of_nodes = self.make_all_child_nodes(model) for node in list_of_nodes: output.append(self.check_board_state(node)) return output def return_dictionary_of_scores(self, model, depth, max_depth): if depth == 1: return self.return_all_child_nodes_scores(model) if depth == max_depth: output = {} nodes = self.make_all_child_nodes(model) for node in nodes: output[node] = self.return_dictionary_of_scores(node, depth-1, max_depth) return output output = [] for node in self.make_all_child_nodes(model): output.append(self.return_dictionary_of_scores(node, depth-1, max_depth)) return output def flatten_dictionary(self, dictionary_or_list, depth, max_depth): if depth == max_depth: output = {} for model in dictionary_or_list: output[model] = self.flatten_dictionary(dictionary_or_list[model], depth-1, max_depth) return output if depth == 1: if (max_depth-depth) % 2 == 1: return min(dictionary_or_list) elif (max_depth-depth) % 2 == 0: return max(dictionary_or_list) output = [] for entry in dictionary_or_list: if (max_depth-depth) % 2 == 1: output.append(self.flatten_dictionary(entry, depth-1, max_depth)) return min(output) elif (max_depth-depth) % 2 == 0: output.append(self.flatten_dictionary(entry, depth-1, max_depth)) return max(output) def return_model_to_scores(self, model, depth): dictionary_of_scores = self.return_dictionary_of_scores(model, depth, depth) return self.flatten_dictionary(dictionary_of_scores, depth, depth) def convert_model_to_move(self, model): master_model = self.model res = master_model.pieces.find_orig_space_and_new_space(model.pieces) orig_space = res[0] new_space = res[1] piece = self.model.pieces.get_piece_from_position(orig_space) return [piece, new_space] def find_best_move(self, model, depth): dictionary = self.return_model_to_scores(model, depth) score = 0 model = None for key in dictionary: if dictionary[key]>score: score = dictionary[key] model = key move_rec = self.convert_model_to_move(model) return [move_rec, score] class Model: def __init__(self): self.pieces = Pieces() self.selected = None self.turn = 'White' self.white_win = False self.black_win = False self.all_valid_moves = self.check_all_valid_moves() self.ai = AI('Black', self) def check_move(self, piece, space): model = copy.deepcopy(self) orig_spot = piece.pos new_piece = model.pieces.get_piece_from_position(orig_spot) model.pieces.move(new_piece, space) return not model.check_king_threatened(new_piece.team) def check_king_threatened(self, team): if team == 'White': if self.pieces.wk.pos in self.pieces.get_threatened_by_black(): return True if team == 'Black': if self.pieces.bk.pos in self.pieces.get_threatened_by_white(): return True return False def change_turn(self): if self.turn == 'White': self.turn = 'Black' elif self.turn == 'Black': self.turn = 'White' def check_all_valid_moves(self): output = {} for piece in self.pieces.pieces: moves = [] for move in piece.valid_moves(self.pieces): if self.check_move(piece, move): moves.append(move) if isinstance(piece, King): castle_moves = self.castle_moves(piece) if castle_moves != []: moves.extend(castle_moves) output[piece] = moves return output def castle_moves(self, piece): moves = [] if piece.moved == False: if piece.team == 'White': if piece.pos not in self.pieces.get_threatened_by_black(): rooks = [self.pieces.wr1, self.pieces.wr2] if rooks[0].moved == False: pos = (piece.pos[0], piece.pos[1]-1) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_black(): pos = (piece.pos[0], piece.pos[1]-2) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_black(): pos = (piece.pos[0], piece.pos[1]-3) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_black(): pos = (piece.pos[0], piece.pos[1]-2) moves.append(pos) if rooks[1].moved == False: pos = (piece.pos[0], piece.pos[1]+1) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_black(): pos = (piece.pos[0], piece.pos[1]+2) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_black(): moves.append(pos) if piece.team == 'Black': if piece.pos not in self.pieces.get_threatened_by_white(): rooks = [self.pieces.br1, self.pieces.br2] if rooks[0].moved == False: pos = (piece.pos[0], piece.pos[1]-1) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_white(): pos = (piece.pos[0], piece.pos[1]-2) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_white(): pos = (piece.pos[0], piece.pos[1]-3) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_white(): pos = (piece.pos[0], piece.pos[1]-2) moves.append(pos) if rooks[1].moved == False: pos = (piece.pos[0], piece.pos[1]+1) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_white(): pos = (piece.pos[0], piece.pos[1]+2) if self.pieces.get_piece_from_position(pos) == None and pos not in self.pieces.get_threatened_by_white(): moves.append(pos) return moves def castle(self, pos): if self.selected.team == 'White': if pos == (self.selected.pos[0], self.selected.pos[1]-2): self.pieces.move(self.pieces.wr1, (pos[0], pos[1]+1)) self.move(pos) return if pos == (self.selected.pos[0], self.selected.pos[1]+2): self.pieces.move(self.pieces.wr2, (pos[0], pos[1]-1)) self.move(pos) return if self.selected.team == 'Black': if pos == (self.selected.pos[0], self.selected.pos[1]-2): self.pieces.move(self.pieces.br1, (pos[0], pos[1]+1)) self.move(pos) return if pos == (self.selected.pos[0], self.selected.pos[1]+2): self.pieces.move(self.pieces.br2, (pos[0], pos[1]-1)) self.move(pos) return def get_valid_moves(self, piece): dictionary = self.all_valid_moves moves = dictionary[piece] return moves def move(self, space): piece = self.selected if self.turn == piece.team: if space in self.get_valid_moves(piece): self.pieces.move(piece, space) if isinstance(piece, Pawn): print "pawn moved" print space if piece.team == "White" and space[0]==1: print "became queen" piece = Queen(piece.pos, piece.team) self.check_win(piece.team) self.change_turn() self.selected = None self.all_valid_moves = self.check_all_valid_moves() def check_win(self, team): valid_moves = [] if team == 'White': for piece in self.pieces.black_pieces: moves = self.get_valid_moves(piece) if moves != []: valid_moves.append(moves) if valid_moves == []: self.white_win = True return True if team == 'Black': for piece in self.pieces.white_pieces: moves = self.get_valid_moves(piece) if moves != []: valid_moves.append(moves) if valid_moves == []: self.white_win = True return True class View: def __init__(self, model, screen): self.model = model self.screen = screen self.wp = pygame.transform.scale(pygame.image.load("sprites/white_pawn.png"), (size[0]/8, size[1]/8)) self.wr = pygame.transform.scale(pygame.image.load("sprites/white_rook.png"), (size[0]/8, size[1]/8)) self.wb = pygame.transform.scale(pygame.image.load("sprites/white_bishop.png"), (size[0]/8, size[1]/8)) self.wkn = pygame.transform.scale(pygame.image.load("sprites/white_knight.png"), (size[0]/8, size[1]/8)) self.wq = pygame.transform.scale(pygame.image.load("sprites/white_queen.png"), (size[0]/8, size[1]/8)) self.wk = pygame.transform.scale(pygame.image.load("sprites/white_king.png"), (size[0]/8, size[1]/8)) self.bp = pygame.transform.scale(pygame.image.load("sprites/black_pawn.png"), (size[0]/8, size[1]/8)) self.br = pygame.transform.scale(pygame.image.load("sprites/black_rook.png"), (size[0]/8, size[1]/8)) self.bb = pygame.transform.scale(pygame.image.load("sprites/black_bishop.png"), (size[0]/8, size[1]/8)) self.bkn = pygame.transform.scale(pygame.image.load("sprites/black_knight.png"), (size[0]/8, size[1]/8)) self.bq = pygame.transform.scale(pygame.image.load("sprites/black_queen.png"), (size[0]/8, size[1]/8)) self.bk = pygame.transform.scale(pygame.image.load("sprites/black_king.png"), (size[0]/8, size[1]/8)) def draw_board(self): self.screen.fill(pygame.Color(139,69,19)) for i in range(4): for j in range(4): pygame.draw.rect(self.screen, (255,255,255), (size[0]*i/4, size[1]*j/4, size[0]/8, size[1]/8)) for i in range(4): for j in range(4): pygame.draw.rect(self.screen, (255,255,255), (size[0]*i/4+size[0]/8, size[1]*j/4+size[1]/8, size[0]/8, size[1]/8)) def draw(self): self.draw_board() self.draw_moves() for piece in self.model.pieces.pieces: self.draw_piece(piece) def draw_moves(self): if self.model.selected == None: return if self.model.get_valid_moves(self.model.selected) != []: self.draw_red(self.model.selected.pos) self.draw_square_small(self.model.selected.pos) for move in self.model.get_valid_moves(self.model.selected): self.draw_red(move) self.draw_square_small(move) def draw_red(self, space): color = (255,255,0) pos = [size[0]*(space[1]-1)/8.0, size[1]*(space[0]-1)/8.0] pygame.draw.rect(self.screen, color, (pos[0], pos[1], size[0]/8.0, size[1]/8.0)) def draw_square_small(self, space): if (space[0]+space[1])%2 == 0: color = (255,255,255) else: color = (139,69,19) pos = [size[0]*(space[1]/8.0)-size[0]*15/16.0/8.0, size[1]*(space[0]/8.0)-size[1]*15/16.0/8.0] pygame.draw.rect(self.screen, color, (pos[0], pos[1], size[0]*7/8.0/8.0, size[1]*7/8.0/8.0)) def draw_piece(self, piece): if isinstance(piece, King): if piece.team == 'Black': sprite = self.bk elif piece.team == 'White': sprite = self.wk if isinstance(piece, Queen): if piece.team == 'Black': sprite = self.bq elif piece.team == 'White': sprite = self.wq if isinstance(piece, Knight): if piece.team == 'Black': sprite = self.bkn elif piece.team == 'White': sprite = self.wkn if isinstance(piece, Bishop): if piece.team == 'Black': sprite = self.bb elif piece.team == 'White': sprite = self.wb if isinstance(piece, Rook): if piece.team == 'Black': sprite = self.br elif piece.team == 'White': sprite = self.wr if isinstance(piece, Pawn): if piece.team == 'Black': sprite = self.bp elif piece.team == 'White': sprite = self.wp pos = (size[0]/8.0*(piece.pos[1]-1), size[1]/8.0*(piece.pos[0]-1)) self.screen.blit(sprite, pos) class Controller: def __init__(self, model, view): self.model = model self.view = view def handle_pygame_event(self, event): if event.type == MOUSEBUTTONUP: mouse_position = pygame.mouse.get_pos() click_position = self.mouse_position_to_position(mouse_position) piece = self.model.pieces.get_piece_from_position(click_position) secondConditional = True if piece != None: if piece.team == self.model.turn: self.model.selected = piece secondConditional = False if secondConditional: if self.model.selected != None: #print self.model.get_valid_moves(self.model.selected) if click_position in self.model.selected.valid_moves(self.model.pieces): self.model.move(click_position) elif click_position in self.model.get_valid_moves(self.model.selected): print 'ayy' self.self.model.castle(click_position) if self.model.white_win: self.view.draw_board() elif self.model.black_win: self.view.draw_board() else: self.view.draw() pygame.display.update() if self.model.turn == self.model.ai.team: [[piece, move], score] = self.model.ai.find_best_move(self.model, 2) self.model.selected = piece self.model.move(move) def mouse_position_to_position(self, mouse_position): x = mouse_position[0] sizex = size[0]/8.0 y = mouse_position[1] sizey = size[1]/8.0 for i in range(8): for j in range(8): if sizex*i<=x<=sizex*(i+1): if sizey*j<=y<=sizey*(j+1): return (j+1, i+1) if __name__ == "__main__": pygame.init() pygame.display.set_caption("Chess") screen = pygame.display.set_mode(size) model = Model() view = View(model, screen) controller = Controller(model, view) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() controller.handle_pygame_event(event) if model.white_win: view.draw_board() elif model.black_win: view.draw_board() else: view.draw() pygame.display.update()
1ed6a71caebc66136df44815b45e017191e2bb39
jbtanguy/JBTools
/JBTools/evaluate_ocr_results.py
5,433
3.75
4
import os import io import subprocess def get_txt_from_file(file_name): """This function only reads a file and returns its containt. @param: file_name (string): path to the file @return: txt (string): text read in <file_name> """ txt = '' file = io.open(file_name, mode='r', encoding='utf-8') txt += file.read() file.close() return txt def get_txt_from_dir(dir_name): """This function, given a directory, returns a dictionary as: - keys: file_name (found in <dir_name>) - values: text read in <file_name> @param: dir_name (string): path to the directory we want to get the texts @returns: res (directory): see above. """ file_names = [n for n in os.listdir(dir_name) if '.txt' in n] res = {f:get_txt_from_file(dir_name+f) for f in file_names} return res def parse_asrtoolkit_result(res): """This function returns the asrtoolkit result (cer or wer) as follow: 'CER: 4%' --> 4 @param: res (string): the string that asrtoolkit returns @return: res_net (float): only the number """ res_net = str(res) for s in ['WER: ', 'CER: ', '%\\n', '\'', 'b']: res_net = res_net.replace(s, '') return float(res_net) def cer_wer(file_ref, file_test): """This function processes, using the asrtoolkit, the character error rate and the word error rate, given a reference text file and a file to test. @param: file_ref (string): path to the reference text @param: file_test (string): path to the text to test @return: error_rates (tuple): (cer, wer) """ # Character Error Rate cer_cmd = 'wer ' + file_ref + ' ' + file_test + ' --char-level' cer_res = subprocess.check_output(cer_cmd, shell=True) cer = parse_asrtoolkit_result(cer_res) # Word Error Rate wer_cmd = 'wer ' + file_ref + ' ' + file_test wer_res = subprocess.check_output(wer_cmd, shell=True) wer = parse_asrtoolkit_result(wer_res) return (cer, wer) def cer_wer_from_directories(dir_ref, dir_test): """This function allows the user to process cer and wer for several files at the same time. But the files in <dir_test> must be aligned to the files in <dir_ref>, aligned by their names... @param: dir_ref (string): path to the directory in which the reference files are stored @param: dir_test (string): path to the directory in which the test files are stored @return: res (dictionary): dictionary in which the (cer, wer) are stored (key=(path_ref, path_test), values=(cer, wer)) """ res = {} ref_files = sorted([n for n in os.listdir(dir_ref) if '.txt' in n]) test_files = sorted([n for n in os.listdir(dir_test) if '.txt' in n]) root_names = [n.replace('.txt', '') for n in ref_files] # Here, we assume that the ref files names are # "root"=in all the test files we can find the # root and something more as suffixe. for root in root_names: r = dir_ref + root + '.txt' t = '' # We try to find the test file associated to the ref file for file in test_files: if root in file: t = dir_test + file if t != '': res[(r, t)] = cer_wer(r, t) return res def get_sequencies(txt, length): """Given a raw text (string), this function returns all the sequencies we can find by a sliding window. @param: txt (string) @param: length (int) @return: sequencies (list) """ raw_text = txt.replace('\n', ' ') sequencies = [] for i in range(length, len(raw_text)): seq = raw_text[i-length:i+1] # A sequence of characters sequencies.append(seq) return sequencies def global_proba_with_model(txt_file, model, ngrams): """This function calculates, for a sequence (length=ngrams), the probabiblity to have the next character, given a language model. And this is done for the entire text, with a sliding window. @param: txt_file (string): file in which the text is stored @param: model (LanguageModel): the language model, neural with the Keras library or only probabilistic: it's used to predict the next character given a sequence @param: ngrams (int): this is the length the model was learnt with @return: proba (float): the sum of all the probabilities calculated for the entire text with the given model """ proba = 0 txt = get_txt_from_file(txt_file) sequencies = get_sequencies(txt, ngrams) for i in range(len(sequencies) - 1): proba += model.get_proba(sequencies[i], sequencies[i + 1][0]) return proba def proba_per_line_with_model(txt_file, model, ngrams): """This function calculates, for a sequence (length=ngrams), the probabiblity to have the next character, given a language model. And this is done for every lines in the text, with a sliding window. BUT: the number of characters might be inferior than the ngrams; in this case, the function give -1. @param: txt_file (string): file in which the text is stored @param: model (LanguageModel): the language model, neural with the Keras library or only probabilistic: it's used to predict the next character given a sequence @param: ngrams (int): this is the length the model was learnt with @return: probas (dictionary): keys=nb_line, values=sum of the probas for this line """ probas = {} txt = get_txt_from_file(txt_file) lines = txt.split('\n') cnt = 1 # line counter for line in lines: line_name = 'line' + str(cnt) proba = -1 sequencies = get_sequencies(line, ngrams) if len(sequencies) > 2: proba = 0 for i in range(len(sequencies) - 1): proba += model.get_proba(sequencies[i], sequencies[i + 1][0]) probas[line_name] = proba cnt += 1 return probas
766dd3499166fafcc2acc49969aad5b8b4c94fa4
tohungsze/Python
/other_python/sort_quick.py
4,073
4.28125
4
""" quick sort """ # find pivot point where everything smaller than it is on the left of it # everything larger than it is on the right # Put everything smaller than the pivot in a list # Put everything larger than the pivot in another # Put everything equal to the pivot in final list # Run quick sort again on the smaller list and larger list until they are all sorted # In a random input list, every element is as good an element to start as any other # Randomizing position of pivot makes it more likely to avoid picking the worse case(?) # best case: nlog(n) # worst case: n**2 (input is an already sorted list) # also included two functions - one manually tracking the pivot, one with built-in function # built-in function in Python 3 is much, much faster than either of the manually created method import random import time def sort_quick(a): if len(a) <= 1: return a smaller, equal, larger = [], [], [] pivot = a[random.randint(0, len(a) - 1)] # randint is a method in Python 3 for x in a: if x < pivot: smaller.append(x) elif x == pivot: equal.append(x) elif x > pivot: larger.append(x) return sort_quick(smaller) + equal + sort_quick(larger) # test li = [3, 2, 1, 4] li1 = [5, 7, 2, 9, 3, 1, 4, 6, 8] # [1, 2, 3, 4, 5, 6, 7, 8, 9] li2 = [1, 2, 3, 4] li3 = [1, 10, 2, 2, 3, 4] print(sort_quick(li)) print(sort_quick(li1)) print(sort_quick(li2)) print(sort_quick(li3)) # time taken #x = 10_000_000 x = 100 li4 = [] li4a = [] li5 = [] li5a = [] li6 = [] for i in range(x): n = random.randint(0, x) li4.append(n) li5.append(n) li6.append(n) # print(sort_quick(li4)) start_time = time.time() li4a = sort_quick(li4) end_time = time.time() time_taken = end_time - start_time print("li4 before sort:", li4) print("li4a after sort", li4a) print(f"time taken to quick sort list of", len(li4), "with method 1:", "{:.2f}".format(end_time - start_time), "sec") # repeat on sorted list start_time = time.time() sort_quick(li4a) end_time = time.time() print(f"time taken to quick sort list of SORTED", len(li4), "with method 1:", "{:.2f}".format(end_time - start_time), "sec") print() # from internet def sort_quick_pivot(arr): elements = len(arr) # Base case if elements < 2: return arr current_position = 0 # Position of the partitioning element for i in range(1, elements): # Partitioning loop if arr[i] <= arr[0]: current_position += 1 temp = arr[i] arr[i] = arr[current_position] arr[current_position] = temp temp = arr[0] arr[0] = arr[current_position] arr[current_position] = temp # Brings pivot to it's appropriate position left = sort_quick_pivot(arr[0:current_position]) # Sorts the elements to the left of pivot right = sort_quick_pivot(arr[current_position + 1:elements]) # sorts the elements to the right of pivot arr = left + [arr[current_position]] + right # Merging everything together return arr start_time = time.time() li5a = sort_quick_pivot(li5) end_time = time.time() print("li5 before sort", li5) print("li5a after sort", li5a) print(f"time taken to quick sort list of", len(li4), "with method 2:", "{:.2f}".format(end_time - start_time), "sec") # repeat on sorted list - can't run this on 20,000 already sorted list => too many partitions # start_time = time.time() # sort_quick_pivot(li5a) # end_time = time.time() # print(f"time taken to quick sort list of SORTED", len(li5), "with method 2:", "{:.2f}".format(end_time - start_time), "sec") # print() # using built-in print("li6 before sort:", li6) start_time = time.time() li6.sort() end_time = time.time() print(f"time taken to quick sort list of", len(li6), "using BUILT-IN function:", "{:.2f}".format(end_time - start_time), "sec") print("li6 after sort: ", li6) start_time = time.time() li6.sort() end_time = time.time() print(f"time taken to quick sort list of SORTED", len(li6), "using BUILT-IN function:", "{:.2f}".format(end_time - start_time), "sec")
0b2ff5322d8fecace0fe084077e02c94a5f76208
Adarsh2412/python-
/python6.py
91
3.78125
4
a=int(input("Enter a number")) b=int(input("Enter 2nd number")) c=a+b print(type(a),c)
321a781da1a1a3fed8efe0f610ca44f70f99acef
loetcodes/100-Days-of-Code---PythonChallenge-01
/Day_40_RecursiveListReverse.py
1,074
4.375
4
""" Day 40 - Recursive list reverse Write a function list_reverse(my_list) that takes a list and returns a new list whose elements appear in reversed order. For example, list_reverse([2,3,1]) should return [1,3,2]. Do not use the reverse() method for lists. """ #!/bin/python3 def list_reverse(my_list): """ Takes a list and reverses the list without using the reverse method. Returns a reversed list """ if len(my_list) <= 1: return my_list else: n = [my_list[-1]] return n + list_reverse(my_list[:-1]) def test_list_reverse(): """ Some test cases for list reverse """ print ("Computed:", list_reverse([1,2,3,4]), "Expected: ", [4, 3, 2, 1]) print ("Computed:", list_reverse([0,2,2,1]), "Expected: ",[1, 2, 2, 0]) print ("Computed:", list_reverse([]), "Expected: ", []) print ("Computed:", list_reverse([4]), "Expected: ", [4]) print ("Computed:", list_reverse(['i', 'd', 'g', 'a', 'f']), "Expected: ", ['f', 'a', 'g', 'd', 'a']) if __name__ == '__main__': test_list_reverse()
cb3f5b375355d5760f2f746a65cc758ecf8cf9a0
Asmita-Malakar/PythonProjects
/manage_course_new/course.py
1,192
4.03125
4
#Asmita Malakar #7/11/2021 #Setter method and private variable class Course: def __init__(self, course_code, max_size, enrollment): self.__course_name = course_code self.__size = int(max_size) self.__enrollment = enrollment def add_student(self): if self.__enrollment >= self.__size: print("Course already full.") else: self.__enrollment = self.__enrollment + 1 print("One student added.") def drop_student(self): if self.__enrollment <= 0: print("Course is empty.") else: self.__enrollment = self.__enrollment - 1 print("One student dropped.") def get_class_size(self): return self.__size def get_class_enrollment(self): return self.__enrollment def set_newSize(self, newSize): self.newClassSize = int(newSize) if self.newClassSize < 0: print("maximum class size cannot be negative") elif self.newClassSize < self.__enrollment: print("maximum class size cannot be lower than current enrollment") else: self.__size = self.newClassSize
2cb35355081313291659c9865f69abab609c2bb7
vatsan1993/Python-Concepts
/sqliteExample/EmployeeBase.py
537
3.703125
4
class Employee: def __init__(self, first, last, pay): self._first= first self._last=last self._pay= pay @property def last(self): return self._last @property def first(self): return self._first @property def fullname(self): return self.first+" "+self.last @property def pay(self): return self._pay @first.setter def first(self, first): self._first=first @last.setter def last(self, last): self._last=last
bad99d29469299ec5cc386dd70061e1325290499
libra202ma/cc150Python
/chap09 Recursion and Dynamic Programming/9_01.py
1,090
4.34375
4
""" A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. - same as representing n cents using coins. - whoops, not really. The sequence of hops matters. On the last hop, up to the n-th step, the child could have done either a single, double, or triple step hop. And dynamic programming can be used to reduce subfunction calls. """ def countways(n): if n < 0: return 0 elif n == 0: return 1 else: return countways(n - 1) + countways(n - 2) + countways(n - 3) def test_countways(): assert countways(1) == 1 assert countways(2) == 2 assert countways(3) == 4 def countwaysDP(n, maps={}): if n < 0: return 0 elif n == 0: return 1 elif n in maps: return maps[n] else: maps[n] = countways(n - 1, maps) + countways(n - 2, maps) + countways(n - 3, maps) return maps[n] def test_countwaysDP(): assert countways(1) == 1 assert countways(3) == 4
e04ce950aaf0bea28e86dc1ef5f94c7452a2de18
jibranabduljabbar/Python-3-Crash-Course
/Complete_Python.py
46,626
4.03125
4
# What Is Python? """ + Python Is a Popular Programming Language. It was created by Guido van Rossum, And Released In 1991. + Python Is a Interpreted Language. + It Is Used For: + 1): Web Development (Server-Side), + 2): Software Development, + 3): Mathematics, + 4): System Scripting. # What can Python do? + Python can be used on a server to create web applications. + Python can be used alongside software to create workflows. + Python can connect to database systems. It can also read and modify files. + Python can be used to handle big data and perform complex mathematics. + Python can be used for rapid prototyping, or for production-ready software development. # Why Python? + Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). + Python has a simple syntax similar to the English language. + Python has syntax that allows developers to write programs with fewer lines than some other programming languages. + Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. + Python can be treated in a procedural way, an object-oriented way or a functional way. # Python Syntax compared to other programming languages: + Python was designed for readability, and has some similarities to the English language with influence from mathematics. + Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. + Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. # Installing Python Setup: + Download Anaconda Navigator Website_Name Go(https://www.anaconda.com/products/individual#Downloads). Then Selected Option (Window, MacOS, Linux). + Download Completed Then Opon Anaconda Then Accept All Argrements Then Open Anaconda Then Launch ((Jupyter)NoteBook) Version(6.3.0). + Then Open Jupyter in Google then Press New Button then Select Option (Python 3) + Then Your Browser In Always Open This Https: (http://localhost:8888/notebooks/Untitled1.ipynb?kernel_name=python3) + Then Write Your Coading Inside (In[]: Input) # For Example: Press Run Button ⬇️ * print("Hello World") ===> Output Is: (Hello World) # No Need: + No need of var int or double in python. + variable declearation. + variable initiallization. # Variable: + Variables are containers for storing data values. + A variable is created the moment you first assign a value to it. + Variables do not need to be declared with any particular type, and can even change type after they have been set. # For Example: (a) Is a Variable Name Equal (Operator) (5) Is Value Of (a) Variable ⬇️⬇️⬇️ * a = 5 ===> Varible Inside Value. * print(a) ===> Print (a) Variable Value. # Work On: * VariableName = Value # String Expression: * populor_string = "This Is String Value" * print(populor_string) # Math Expression: * populor_number = 5 * print(populor_number) # Math Expression: Familiar Operators: # Addition: * addition = 5 + 5 * print(addition) # 10 # Subtraction: * subtraction = 15 - 5 * print(subtraction) # 10 # MultipliCation: * multipliCation = 5 * 2 * print(multipliCation) # 10 # Division: * division = 15 / 5 * print(division) # 3.0 # Module: * module = 20 % 6 * print(module) # 2 # Decimal Value: * num = .075 ===> This Is a Decimal Value. * total = num + 200 ===> Concatenating. * print(total) ===> 200.075 # Variable Names Legal & Illegal: + You've already learned three rules about naming a variable: 1. You can't enclose it in quotation marks. 2. You can't have any spaces in it. 3. It can't be a number or begin with a number. + In addition, a variable can't be any of Python's reserved words, also known as keywords—the special words that act as programming instructions, like print. Here’s a list of them. # and False not # as finally or # assert for pass # break from print # class global raise # continue if return # def import True # del in try # elif is while # else lambda with # except none yield # nonlocal # Code: * a = 5 * a = a+1 * print(a) ===> Output Is: (6) # Same Work: * a = 10 * a += 2 * print(a) ===> Output Is: (12) # Math Expresstion: Eliminating Ambiguity(DMAS Rule): * dmas = 1 + 3 * 4 * print(dmas) ===> Output Is: (13) * dmas = (1 + 3) * 4 * print(dmas) ===> Output Is: (16) * dmas = (1 + 3) * 4 / 2 * print(dmas) ===> Output Is: (8.0) * dmas = (1 + 3) * 4 // 2 * print(dmas) ===> Output Is: (8) # Assignment No_(1): + Step_(1): * print("Twinkle, twinkle, little star, ") * print(" How I wonder what you are!") * print(" Up above the world so high, ") * print(" Like a diamond in the sky. ") * print("Twinkle, twinkle, little star,") * print(" How I wonder what you are") + Second Optioin(One print Of Code) * print("Twinkle, twinkle, little star,\n How I wonder what you are!\n Up above the world so high, \n Like a diamond in the sky. \nTwinkle, twinkle, little star,\n How I wonder what you are") + Step_(2): * version = "3.8.8 (default, Apr 13 2021, 15:08:07) [MSC v.1916 32 bit (Intel)]" * print(version) + Output Is: + 3.8.8 (default, Apr 13 2021, 15:08:07) [MSC v.1916 32 bit (Intel)] + Second Option("Import Sys") * import sys * print(sys.version) + Output Is: + 3.8.8 (default, Apr 13 2021, 15:08:07) [MSC v.1916 32 bit (Intel)] + Step_(3): * text = "Current Date And Time: " * date = "2021-05-16 04:12:38" * print(text) * print(date) + Output Is: + Current Date And Time: + 2021-05-16 04:12:38 + Second Option("Import DateTime") * import datetime * now = datetime.datetime.now() * print("Current Date And Time: ") * print(now.strftime("%Y-%m-%d %H:%M:%S")) + Output Is: + Current Date And Time: + 2021-05-16 04:12:38 + Step_(4): * + Step_(5): * firstname = "Mark" * lastname = "Myers" * print("Fullname Is: " + lastname +" "+ firstname) + Output Is: + Fullname Is: Myers Mark + Second Option("Input Throw") * firstname = input("Enter your Firstname: ") * lastname = input("Enter your Lastname: ") * print("Fullname Is: " + lastname +" "+ firstname) + Output Is: + Fullname Is: Myers Mark + Step_(6): * num1 = 18 * num2 = 2 * print(num1+num2) + Output Is: + 20 + Second Option("Input Throw") * num1 = input("Enter your num1: ") * num2 = input("Enter your num2: ") * print(int(num1)+int(num2)) + Output Is: + 20 # Assignment No_(1) Is Completed # Concatenation * str = "Jibran" * str1 = "Abdul Jabbar" * punc = "!" * print(str + ' ' + str1 + " " + punc) # Arithmetic Operation * () / * + - ** // % * >>> 20 / 2 * 10.0 (a float?) * >>> 3/0 + ZeroDivisonError: division by Zero * >>> 5 + 3.0 * 8.0 * >>> 2 ** 3 >>> Powered Discuss * 8 + Powered Discuss (**) * num = 5 * num1 = 2 * print(num ** num1) + Output Is: + 25 + Second Option(**) * num = 3 * num1 = 2 * print(num ** num1) + Output Is: + 9 + Third Option(**) * num = 4 * num1 = 2 * print(num ** num1) + Output Is: + 16 # Arithmetic Operation_(Cont) * >>> 15.0 // 2.0 (floor division) * 7 * >>> 15.0 % 2.0 (remainder) * 1 # String (Theory) + A String is created by entering a text between two double quotations or two single quotes. * >>> 'We are Programmers' 'We are Programmers' * Three Quotes String '''Whatever I write here will be displayed as it is''' + String Is a Group Of Character. # String (Cont) >>> print('one,' + ' two,' + ' three') + Output Is: + one, two, three >>> '5' + '3' + Output Is: + 53 (not 8) >>> '1' + 5 + Output Is: + TypeError: unsupported operand types >>> print(" Hello World " * 5) + Output Is: + Hello World Hello World Hello World Hello World Hello World >>> print(5 * " Hello World ") + Output Is: + Hello World Hello World Hello World Hello World Hello World >>> print(" Hello World " * 5.0) + Output Is: + TypeError >>> print('Hello' * 'World') + Output Is: + TypeError # Simple Input/Output >>> print('Python is cool') + Output Is: + Python is cool # Line Break In Python Print >>> print('You are \n Welcome') + Output Is: + You are + Welcome # Variable Input + Input Always take the Values as String. * x = input("Enter your age: ") + Enter your age: 8 >>> print(x) + Output Is: * 8 # Format Function In Python * marks = "79" * percentage = "80.0000000%" * print("Marks: {} - Percentage: {}".format(marks , percentage)) + Output Is: + Marks: 79 - Percentage: 80.0000000% # Float * x = input("Enter your value: ") * y = 18 * z = float(x) + y * print(z) + Output Is: + Enter your value: 5 + 23.0 + Second Option(Use Float ==> input) * x = float(input("Enter your value: ")) * y = 18 * z = x + y * print(z) + Output Is: + Enter your value: 5 + 23.0 # Integer(int ===> Keyword) + Use Int() Function to Convert String into Integer. * x = input("Enter your value: ") * y = 18 * z = int(x) + y * print(z) + Output Is: + Enter your value: 5 + 23 + Second Option(Use Integer ==> input) * x = int(input("Enter your value: ")) * y = 18 * z = x + y * print(z) + Output Is: + Enter your value: 5 + 23 # Single Line Comment (#) # This Is Single Line Comment TexT # Multi Line Comment (""" """) * This Is Multi Line Comment TexT ===> """ """ # IF/Else Statement In Python * age = int(input("Enter your age: ")) * if age >= 15 : * print("You are Allowed To This Ride") * else : * print("You are Not Allowed to This Ride") + Output Is: + Enter your age: 17 + You are Allowed To This Ride + Second Condition * if 2+2 == 4 : * print("2 + 2 Is Equal To 4") + Output Is: + 2 + 2 Is Equal To 4 # Comparison Operators * a = 5 * b = 15 * c = 5 * d = 5 * if a+d == b-c : * print("Your Answer Is Correct..!") * else : * print("Your Answer Is WronG..!") + Output Is: + Your Answer Is Correct..! # Not Equal To Operator * a = 5 * b = 15 ==> 22 * c = 5 * d = 5 ==> 20 * if a+d != b-c : * print("Your Answer Is Correct..!") * else : * print("Your Answer Is WronG..!") + Output Is: + Your Answer Is WronG..! + Here are 4 more comparison operators, usually used to compare numbers. + > Is Greater than + < Is Lass than + >= Is Greater than or Equal to + <= Is Less than or Equal to + In the Examples below, all the Conditions are True. * if 1 > 0 : * if 0 < 1 : * if 1 >= 0 : * if 1 >= 1 : * if 0 <= 1 : * if 1 <= 1 : # Else/ElIF Statement * course_name = input("Enter Your CourSe Name: ") * if course_name == "Python" : * print("Python Is Cool") * elif course_name == "JavaScript" : * print("JavaScript Is Cool") * elif course_name == "HTML & CSS" : * print("HTML & CSS") * else : * print("All Courses Is COOL..!") + Output Is: + Enter Your CourSe Name: Python + Python Is Cool # (IF/Else/ElIF) Statement Percentage Example Uses (and/or) * percent = int(input("Enter Your Percent: ")) * if percent >= 80 and percent <= 100 : * print("A+") * elif percent >= 70 and percent <= 80 : * print("A") * elif percent >= 60 and percent <= 70 : * print("B") * elif percent >= 50 and percent <= 60 : * print("C") * elif percent >= 40 and percent <= 50 : * print("D") * elif percent >= 33 and percent <= 40 : * print("E") * elif percent >= 0 and percent <= 33 : * print("Fail") * else : * print("You have given Inapproperiate Percentage_(%) ") # (IF/Else/ElIF) Statement Simple CalCulator Example Uses (and/or) * num1 = int(input("Enter Your Num1: ")) * operator = input("Enter Your Operator: ") * num2 = int(input("Enter Your Num2: ")) * if operator == "+" : * print("Answer Is: ", num1 + num2) * elif operator == "-" : * print("Answer Is: ", num1 - num2) * elif operator == "*" : * print("Answer Is: ", num1 * num2) * elif operator == "/" : * print("Answer Is: ", num1 / num2) * elif operator == "%" : * print("Answer Is: ", num1 % num2) * else : * print("Make a Mistake!") # (IF/Else/ElIF) Statement Prize Bond Example Uses (and/or) * ticket_luck = int(input("Enter your Ticket No: ")) * if ticket_luck == 18341 : * print("Congratulations (1st Prize) Price: ($50000)") * elif ticket_luck == 18342 : * print("Congratulations (2nd Prize) Price: ($30000)") * elif ticket_luck == 18343 : * print("Congratulations (3rd Prize) Price: ($10000)") * else : * print("Bad Luck Next Time Try Again") # Nested (IF/Else/ElIF) Statement: * a = 5; * b = 6; * c = 7; * d = 7; * e = 9; * g = 10; * f = 11; * x = 12; * y = 12; * h = 0; * if (x == y or a == b) and c == d : ==> ( (x == y ==> 12 == 12) or (a == b ==> 5 == 6) ) and (c == d ==> 7 == 7) * g = h * print(g) * else : * e = f * print(e) # Second Condition Same Condition (Nested (IF/Else/ElIf)) * a = 5; * b = 6; * c = 7; * d = 7; * e = 9; * g = 10; * f = 11; * x = 12; * y = 12; * h = 0; * if c == d : * if a == b : * g = h * print(g) * elif x == y : * g = h * print(g) * else : * e = f * else: * e = f # List (Array) + We can store one or more elements in the list. + List & Array Is a Group of Element. + Each element in the list has a unique id through which we see the value of that ID. + Lists are created using square brackets: * arr = ["Array",1,False,"List",1.33,True] * print(arr) + Output Is: + ['Array', 1, False, 'List', 1.33, True] # Array_(Indexs) * arr = ["Array",1,False,"List",1.33,True] * print(arr[3]) + Output Is: + List # Find the Length of List in Python_(len) * list = ["HTML","CSS","JavaScript","EcmaScript","React Js","Redux","React Native","Firebase","Github","Bootstrap","Linux"] * print(len(list)) + Output Is: + 11 # Element Add Inside List_(append) * arr = ["Array",1,False,"List",1.33,True] * arr.append("React") * print(arr) + Output Is: + ['Array', 1, False, 'List', 1.33, True, 'React'] # Multiples Elements Added Inside List * arr1 = arr + ["JavaScript","HTML & CSS"] * print(arr1) + Output Is: + ['Array', 1, False, 'List', 1.33, True, 'React', 'JavaScript', 'HTML & CSS'] # Get the largest number from a Numeric list_(max). * largest = [65,34,23,67,98,56,87] * print(max(largest)) + Output Is: * 98 + Second Option: * largest = [65,34,23,67,98,56,87] * largest.sort() * print(largest[-1]) + Output Is: + 98 # List_(Array) Inside Insert Elements * arr1.insert(2, "Redux") * print(arr1) + Output Is: + ['Array', 1, 'Redux', False, 'List', 1.33, True, 'React', 'JavaScript', 'HTML & CSS'] # Array_(List) Inside Replace/Add Value * arr1[5] = 1.34 * print(arr1) + Output Is: + ['Array', 1, 'Redux', False, 'List', 1.34, True, 'React', 'JavaScript', 'HTML & CSS'] # List_(Array) Inside Slice Elements + Slicing Is a Flexible tool to Build new Lists Out of an Existing List. + The Slice() Function returns a Slice Object that can use Used to Slice Strings, lists, tuple etc. + To Access a Range of items in a List, you need to Slice a List. + Syntex: * arr2 = arr1[2 : 5] # 5 Means Index No 4 ('List') * print(arr2) + Output Is: + ['Redux', False, 'List'] # Copy Element One Array To Second Array_(Short Cut): * arr = ["Array",1,False,"List",1.33,True] * arr.append("React") * print(arr) * arr3 = arr[:6] * print(arr3) + Output Is: + ['Array', 1, False, 'List', 1.33, True, 'React'] + ['Array', 1, False, 'List', 1.33, True] # List_(Array) Inside (DELETE Method) + Definition & Usage: + The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc. + Syntex: * arr = ["Array",1,False,"List",1.33,True] * del arr[2] * print(arr) + Output Is: + ['Array', 1, 'List', 1.33, True] # List_(Array) Inside (Remove Method) + Definition & Usage: + remove() is an inbuilt function in Python programming language that removes a given object from the list. It does not return any value. + Remove the "Banana" element of the fruit list: * fruits = ['Apple','Banana','Cherry'] * fruits.remove("Banana") * print(fruits) + Output Is: + ['Apple', 'Cherry'] # List_(Array) Inside (Pop Method) + Definition & Usage: + Pop method is used to remove the last element of the list. + Pop () This remove the last element of the list + Remove the second element of the fruit list: * fruits = ['Apple','Banana','Cherry'] * fruits.pop(1) * print(fruits) + Output Is: + ['Apple', 'Cherry'] + Second Example_(Push) + We can also use pop to cover values from one list to another: * list5 = [1,2,3,4,5] * list6 = list5.pop() * print(list6) + Output Is: + 5 # List_(Array) Inside (Sort List Alphanumerically Method) + Definition & Usage: + List objects have a sort() method that will sort the list alphanumerically, ascending, by default: + Sort the list numerically: * sort_method = [3,5,1,4,2,9,6,10,8,7] * sort_method.sort() * print(sort_method) + Output Is: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + Sort the list alphabetically: * sort_method = ["Banana","Apple","Cherry","Watermillon","Orange"] * sort_method.sort() * print(sort_method) + Output Is: + ['Apple', 'Banana', 'Cherry', 'Orange', 'Watermillon'] # List_(Array) Inside (Copy Method) + Definition & Usage: + You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. + There are ways to make a copy, one way is to use the built-in List method copy(). + Make a copy of a list with the copy() method: * copy_method = ["Banana","Apple","Cherry","Watermillon","Orange"] * copy_method1 = copy_method.copy() * print(copy_method1) + Output Is: + ['Banana', 'Apple', 'Cherry', 'Watermillon', 'Orange'] # List_(Array) Inside (List Method) + Definition & Usage: + Another way to make a copy is to use the built-in method list(). + Make a copy of a list with the list() method: * list_method = ["Banana","Apple","Cherry","Watermillon","Orange"] * list_method1 = list(list_method) * print(list_method1) + Output Is: + ['Banana', 'Apple', 'Cherry', 'Watermillon', 'Orange'] # List_(Array) Inside (Sum Method) + Definition & Usage: + Add all items in a list, and return the result: + Example: * Sum = [10,5,15,40,10,20] * print(sum(Sum)) + Output Is: + 100 # List_(Array) Inside (extend Method) + Definition & Usage: + Or you can use the extend() method, which purpose is to add elements from one list to another list: + Use the extend() method to add list2 at the end of list1: * list1 = [1,2,3,4,5] * list2 = [6,7,8,9,10] * list1.extend(list2) * print(list1) + Output Is: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # List_(Array) Inside (Clear Method) + Definition & Usage: + Remove all elements from the fruits list: * list = [1,2,3,4,5,6,7,8,9,10] * print(list) * list.clear() * print(list) + Output Is: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + [] # This Is Empty List. # Assignement No_(2): + Step No_(1): * sub1 = int(input("Enter your English Subject Marks: ")) * sub2 = int(input("Enter your Physics Subject Marks: ")) * sub3 = int(input("Enter your Chemistry Subject Marks: ")) * sub4 = int(input("Enter your Bio Science Subject Marks: ")) * sub5 = int(input("Enter your Math Subject Marks: ")) * total = (sub1+sub2+sub3+sub4+sub5)/5 * if total >= 80 and total <= 100 : * print("A+") * elif total >= 70 and total < 80 : * print("A") * elif total >= 60 and total < 70 : * print("B") * elif total >= 50 and total < 60 : * print("C") * elif total >= 40 and total < 50 : * print("D") * elif total >= 33 and total < 40 : * print("E") * elif total >= 0 and total < 33 : * print("You are Fail!") + Output Is: + Enter your English Subject Marks: 30 + Enter your Physics Subject Marks: 90 + Enter your Chemistry Subject Marks: 70 + Enter your Bio Science Subject Marks: 40 + Enter your Math Subject Marks: 60 + C + Step No_(2): * user = int(input("Enter your Number ")) * if user % 2 == 0 : * print("This Is Even Number") * else : * print("This Is Odd Number") + Output Is: + Enter your Number 152 + This Is Even Number + Step No_(3): * list = ["HTML","CSS","JavaScript","EcmaScript","React Js","Redux","React Native","Firebase","Github","Bootstrap","Linux"] * print(len(list)) + Output Is: + 11 + Step No_(4): * Sum = [10,5,15,40,10,20] * print(sum(Sum)) + Output Is: + 100 + Step No_(5): * largest = [65,34,23,67,98,56,87] * print(max(largest)) + Output Is: * 98 + Second Option: * largest = [65,34,23,67,98,56,87] * largest.sort() * print(largest[-1]) + Output Is: + 98 + Step No_(6): * a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] * for i in a : * if i < 5 : * print(i) + Output Is: + 1 * 1 * 2 * 3 # Assignment_No_(2) Is Completed # Tuples + Definition & Usage: + Tuples are used to store multiple items in a single variable. + Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. + A tuple is a collection which is ordered and unchangeable. + Tuples are written with round brackets. + Example: * tp = ("I","Learned","Python","In",2,"Hours",True) * print(tp) + Output Is: + ('I', 'Learned', 'Python', 'In', 2, 'Hours', True) # Tuples Index * tp = ("I","Learned","Python","In",2,"Hours",True) * print(tp[2]) + Output Is: + Python + Tuples allow duplicate values: * thistuple = ("apple", "banana", "cherry", "apple", "cherry") * print(thistuple[3]) + Output Is: + apple # List & Tuple Difference * List Is Changeble. * But Tuples Is Not Changeble. # Python For Loop + Definition & Usage: + A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). + This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. + With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. + Example: * list = [1,2,3,4,5,6,7,8,9,10] * print(list) * for i in list : * print(i) + Output Is: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + Second Example_(String): * fruits = ["Apple","Mango","Orange","Banana","Watermillon","Cherry","Strawberry"] * for iteration in fruits : * print(iteration) + Output Is: * Apple * Mango * Orange * Banana * Watermillon * Cherry * Strawberry # For_Loop_(Break Method) + Definition & Usage + The break keyword is used to break out a for loop + Example * cleanest_City = ["Karachi","Lahore","Faisalabad","Islamabad","Hyderabad"] * user_City = input("Enter Your City Name: ") * for City in cleanest_City : * if user_City == City : * print(user_City,"Is Cleanest City.") * break * else : * print(user_City,"Is Not Cleanest City.") + Output Is: + Enter Your City Name: Karachi + Karachi Is Cleanest City. # Nested Loop In Python + Definition & Usage: + A nested loop is a loop inside a loop. + The "inner loop" will be executed one time for each iteration of the "outer loop": + Example: * First_Name = ["Ghouse ","Basit","Muhammad Ali","Muhammad","Mark"] * Last_Name = ["Ahmed","Ahmed","Mughal","Umair","Myers"] * Full_Name = [] * for Fe_First_Name in First_Name : # Outer For Loop * for Fe_Last_Name in Last_Name : # Inner For Loop * Full_Name.append(Fe_First_Name + " " + Fe_Last_Name) * * print(Full_Name) + Output Is: * ['Ghouse Ahmed', 'Ghouse Ahmed', 'Ghouse Mughal', 'Ghouse Umair', 'Ghouse Myers', 'Basit Ahmed', 'Basit Ahmed', 'Basit Mughal', 'Basit Umair', 'Basit Myers', 'Muhammad Ali Ahmed', 'Muhammad Ali Ahmed', 'Muhammad Ali Mughal', 'Muhammad Ali Umair', 'Muhammad Ali Myers', 'Muhammad Ahmed', 'Muhammad Ahmed', 'Muhammad Mughal', 'Muhammad Umair', 'Muhammad Myers', 'Mark Ahmed', 'Mark Ahmed', 'Mark Mughal', 'Mark Umair', 'Mark Myers'] # While Loop In Python * num = 0 * while(num <= 10) : * print(num) * num = num +1 + Output Is: + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 # Table Generate Using While Loop * num = 1 * while(num <= 10) : * print("2" +" "+ "x" +" "+ str(num) +" "+ "=" +" "+ str(2*num) ) * num = num + 1 + Output Is: + 2 x 1 = 2 + 2 x 2 = 4 + 2 x 3 = 6 + 2 x 4 = 8 + 2 x 5 = 10 + 2 x 6 = 12 + 2 x 7 = 14 + 2 x 8 = 16 + 2 x 9 = 18 + 2 x 10 = 20 # Integer Number Convert Into Float Number(float,int) + Example: * a = 10 * b = float(a) * print(b) + Output Is: + 10.0 # Integer Number Convert Into String_("10") Number(str) * a = 10 * b = str(a) * c = 15 * d = b + c * print(d) + Output Is: + TypeError: can only concatenate str (not "int") to str # Changing Case_(LowerCase , UpperCase , CapitalizeCase , Title) + Definition & Usage: + In the Changing Case We Talk About The Lower Case & The Upper Case. * lower()- Return a copy of the string with all the cased characters converted to lowercase. * upper()- Return a copy of the string with all the cased characters converted to uppercase. * capitalize()- Return a copy of the string with its first character capitalized and the rest lowercased. + Example_(UpperCase): * a = "MarK" * print(a.upper()) + Output Is: + MARK + Example_(LowerCase): * a = "MarK" * print(a.lower()) + Output Is: + mark + Example_(CapitalizeCase): * a = "MarK" * print(a.capitalize()) + Output Is: + Mark + Example_(Title Same Work (CapitalizeCase)): * a = "MarK" * print(a.title()) + Output Is: + Mark # Dictionary_In_Python + Dictionary is an object that represent is an key/value. + The Dictionary can be declared by using curly braces {}. + And each key-value pair is separated by the commas(,). + Dictionary_Syntex: + var dictionary = { ===> # dictionary = { + "Name": "ExamPle_Name", ===> # "Key" : "Value", + "Roll_No": "1897", ===> # "Key" : "Value", + "Contact_No": "+92111111111" ===> # "Key" : "Value", + }; ===> # }; ===> (SemiColon(;)) + Example: * fruit = {1: "Apple", 2: "Mango", 3: "OranGe", 4: "Banana", 5: "WaterMelon"}; * print(fruit) + Output Is: + {1: 'Apple', 2: 'Mango', 3: 'OranGe', 4: 'Banana', 5: 'WaterMelon'} # Access Particular Property Inside Dictionary: * Student = {"Firstmame": "Jibran", "Lastname": "Abdul Jabbar", "Roll no": 1834, "Coaching": "BMJ_(Bantva Memon Jamat Education)", "Contact no": "+921111111122"}; * print(Student["Coaching"]) + Output Is: + BMJ_(Bantva Memon Jamat Education) # Dictionary Inside Edit Any Property Value * Student = {"Firstmame": "Jibran", "Lastname": "Abdul Jabbar", "Roll no": 1834, "Coaching": "BMJ_(Bantva Memon Jamat Education)", "Contact no": "+921111111122"}; * Student["Coaching"] = "Saylani Mass IT Training Program" * print(Student) + Output Is: + {'Firstmame': 'Jibran', 'Lastname': 'Abdul Jabbar', 'Roll no': 1834, 'Coaching': 'Saylani Mass IT Training Program', 'Contact no': '+921111111122'} # Dictionary Inside Add Any Property Value * Student = {"Firstmame": "Jibran", "Lastname": "Abdul Jabbar", "Roll no": 1834, "Coaching": "BMJ_(Bantva Memon Jamat Education)", "Contact no": "+921111111122"}; * Student["Batch"] = "5th" * print(Student) + Output Is: + {'Firstmame': 'Jibran', 'Lastname': 'Abdul Jabbar', 'Roll no': 1834, 'Coaching': 'BMJ_(Bantva Memon Jamat Education)', 'Contact no': '+921111111122', 'Batch': '5th'} # Dictionary Inside Remove Any Property * Student = {"Firstmame": "Jibran", "Lastname": "Abdul Jabbar", "Roll no": 1834, "Coaching": "BMJ_(Bantva Memon Jamat Education)", "Contact no": "+921111111122"}; * Student["Batch"] = "5th" * print(Student) * del Student["Batch"] * print(Student) + Output Is: * {'Firstmame': 'Jibran', 'Lastname': 'Abdul Jabbar', 'Roll no': 1834, 'Coaching': 'BMJ_(Bantva Memon Jamat Education)', 'Contact no': '+921111111122', 'Batch': '5th'} * {'Firstmame': 'Jibran', 'Lastname': 'Abdul Jabbar', 'Roll no': 1834, 'Coaching': 'BMJ_(Bantva Memon Jamat Education)', 'Contact no': '+921111111122'} # Print All Keys Inside (Dictionary) Using_(For Loop) * Student = {"Firstmame": "Jibran", "Lastname": "Abdul Jabbar", "Roll no": 1834, "Coaching": "BMJ_(Bantva Memon Jamat Education)", "Contact no": "+921111111122"}; * for keys in Student.keys() : * print(keys) + Output Is: + Firstmame + Lastname + Roll no + Coaching + Contact no # Print All Values Inside (Dictionary) Using_(For Loop) * Student = {"Firstmame": "Jibran", "Lastname": "Abdul Jabbar", "Roll no": 1834, "Coaching": "BMJ_(Bantva Memon Jamat Education)", "Contact no": "+921111111122"}; * for values in Student.values() : * print(values) + Output Is: + Jibran * Abdul Jabbar * 1834 * BMJ_(Bantva Memon Jamat Education) * +921111111122 # Creating a List Of Dictionary + Example: * Questions = [ * { * "S no.": 1, * "Question1": "What Is Your City Name: ", * "Options": ["Karachi","Lahore","Islamabad","Faisalabad","Hyderabad"], * "Answer": "Karachi" * }, * { * "S no.": 2, * "Question2": "What Is Your Batch No: ", * "Options": ["5th","4th","3rd","1st","2nd"], * "Answer": "5th" * }, * { * "S no.": 3, * "Question3": "What Is Your Age: ", * "Options": ["18","7","32","23","12"], * "Answer": "7" * }, * { * "S no.": 4, * "Question4": "What Is Your Country Name: ", * "Options": ["Pakistan","India","America","U.S","Afghanistan"], * "Answer": "Pakistan" * }, * { * "S no.": 5, * "Question5": "Gender: ", * "Options": ["Male","Female","Other"], * "Answer": "Male" * } * ] * print(Questions[0]) + Output Is: + {'S no.': 1, 'Question1': 'What Is Your City Name: ', 'Options': ['Karachi', 'Lahore', 'Islamabad', 'Faisalabad', 'Hyderabad'], 'Answer': 'Karachi'} # Dictionary Inside Get Any Property For Example: * print(Questions[0]["Question1"]) + Output Is: + What Is Your City Name: # Append a new Dictionary in a list of Dictionaries * Questions = [ * { * "S no.": 1, * "Question1": "What Is Your City Name: ", * "Options": ["Karachi","Lahore","Islamabad","Faisalabad","Hyderabad"], * "Answer": "Karachi" * }, * { * "S no.": 2, * "Question2": "What Is Your Batch No: ", * "Options": ["5th","4th","3rd","1st","2nd"], * "Answer": "5th" * }, * { * "S no.": 3, * "Question3": "What Is Your Age: ", * "Options": ["18","7","32","23","12"], * "Answer": "7" * }, * { * "S no.": 4, * "Question4": "What Is Your Country Name: ", * "Options": ["Pakistan","India","America","U.S","Afghanistan"], * "Answer": "Pakistan" * }, * { * "S no.": 5, * "Question5": "Gender: ", * "Options": ["Male","Female","Other"], * "Answer": "Male" * } * ] * new_Dictionary = { * "S no.": 6, * "Question6": "What Is Your Qualification", * "Options": ["Associate","Certificate","B.A.","BArch","BM"], * "Answer": "Certificate" * } * Questions.append(new_Dictionary) * print(Questions[5]) + Output Is: + {'S no.': 6, 'Question6': 'What Is Your Qualification', 'Options': ['Associate', 'Certificate', 'B.A.', 'BArch', 'BM'], 'Answer': 'Certificate'} + List Inside Dictionary Inside Value List Inside Get Any Value Throw Index: * print(Questions[5]["Options"][1]) + Output Is: + Certificate + Insert & Append Method: * Questions.append(new_Dictionary) * Questions.insert(2,new_Dictionary) # Dictionary of Dictionaries + Example: * Students_Data = { * 0: { * "Name": "Basit Ahmed", * "Roll_No": "1875", * "Batch": "2nd", * "Coaching": "Saylani Mass IT Training Program" * }, * 1: { * "Name": "Muhammad Ali Mughal", * "Roll_No": "1876", * "Batch": "2nd", * "Coaching": "Saylani Mass IT Training Program" * }, * 2: { * "Name": "Ghouse Ahmed", * "Roll_No": "1877", * "Batch": "2nd", * "Coaching": "Saylani Mass IT Training Program" * }, * 3: { * "Name": "Muhammad Umair", * "Roll_No": "1878", * "Batch": "2nd", * "Coaching": "Saylani Mass IT Training Program" * }, * } * print(Students_Data[0]) + Output Is: + {'Name': 'Basit Ahmed', 'Roll_No': '1875', 'Batch': '2nd', 'Coaching': 'Saylani Mass IT Training Program'} # Quiz AppliCation Using List Of Dictionary || For Loop || IF Else Condition * Quiz_AppliCation = [ * { * "S no.": "Q_1", * "Question": "Who was the first President of the Constitution Assembly of Pakistan?", * "Options": ["Quaid-e-Azam","Sardar Abdur Rab Nishtar","Liaquat Ali Khan","Moulvi Tameez-ud-Din"], * "Answer": "Quaid-e-Azam" * }, * { * "S no.": "Q_2", * "Question": "After how many years did Pakistan got its first Constitution?", * "Options": ["9 years","7 years","5 years","11 years"], * "Answer": "9 years" * }, * { * "S no.": "Q_3", * "Question": "Who was Mohammad Ali Bogra?", * "Options": ["Prime Minister","Foreign Minister","Parliament Minister","Law Minister"], * "Answer": "Prime Minister" * }, * { * "S no.": "Q_4", * "Question": "When first constitution of Pakistan was enforced?", * "Options": ["23rd March 1956","8th June 1956","14th August 1956","25th December 1956"], * "Answer": "23rd March 1956" * }, * { * "S no.": "Q_5", * "Question": "What official name was given to Pakistan in 1956 constitution?", * "Options": ["Islamic Republic of Pakistan","United States of Pakistan","Islamic Pakistan","Republic of Pakistan"], * "Answer": "Islamic Republic of Pakistan" * }, * { * "S no.": "Q_6", * "Question": "What is the other name of Mohammad Ali Bogra Formula?", * "Options": ["Constitutional Formula","New Law of Pakistan","Pakistan Report","Third Report"], * "Answer": "Constitutional Formula" * }, * { * "S no.": "Q_7", * "Question": "Who was the Prime Minister of Pakistan during enforcement of first constitution?", * "Options": ["Choudhry Mohammad Ali","Mohammad Ali Bogra","Khwaja Nazim Uddin","Ibrahim Ismail Chundrigar"], * "Answer": "Choudhry Mohammad Ali" * }, * { * "S no.": "Q_8", * "Question": "What document was firstly drafted to give pace to constitution making process?", * "Options": ["Objective Resolution","Pakistan Act","Independence Act","Representative Act"], * "Answer": "Objective Resolution" * }, * { * "S no.": "Q_9", * "Question": "What age was prescribed for President in 1956 constitution?", * "Options": ["40 years","55 years","45 years","50 years"], * "Answer": "40 years" * }, * { * "S no.": "Q_10", * "Question": "In respect of religion what term was set for President and Prime Minister in 1956 constitution?", * "Options": ["He must be a Muslim","He may be a Muslim","He must not be Christian","He must not be Hindu"], * "Answer": "He must be a Muslim" * } * ] * * Score = 0 * * for Quiz in Quiz_AppliCation : * Data = Quiz["S no."] + ": " + Quiz["Question"] + "\n" + "* Give your answer in the input field!" + "\n" +"1): "+ Quiz["Options"]* [0] + "\n" +"2): "+ Quiz["Options"][1] + "\n" +"3): "+ Quiz["Options"][2] + "\n" + "4): "+ Quiz["Options"][3] + "\n" + "\n" * User_Answer = input(Data) * if User_Answer == Quiz["Answer"] : * Score += 1 * * print("Your Score Is: " + str(Score) + "\n") # Predefined Function + For Example: * print(), * input(), * insert(), * sort(), * append(), * ETC. # User Defined Functions In Python + Definition & Usage: + A Function is a block of code which only runs when it is called. + You can pass data, known as parameters, into a function. + A function can return data as a result. + Function Is a Very Important Milestone In Any Programming Language. # Creating a Function + In Python a function is defined using the def keyword: * def funcname() : * val = "I am Learning" * val1 = "Python Function" * val2 = "Live now...!" * complete_val = val +" "+ val1 +" "+ val2 * print(complete_val) * funcname() + Output Is: + I am Learning Python Function Live now...! + Second Example: * def addition() : * num_1 = 5 * num_2 = 10 * total = num_1 + num_2 * print(total) * * addition() + Output Is: + 15 # Parameters & Arguments In User Defined Function * def addition(num_1 , num_2) : ===> This Is Parameters. * total = num_1 + num_2 * print(total) * * addition(15 , 5) ===> This Is Arguments. + Output Is: + 20 + Second Example_(Parameters & Arguments): * def addition(num_1 , num_2) : # This Is Parameters * total = num_1 + num_2 <== ==> This Is indentation * print(total) * User_1 = int(input("Enter Your Number: ")) * User_2 = int(input("Enter Your Number1: ")) * addition(User_1 , User_2) # This Is Argument + Output Is: + Enter Your Number: 60 + Enter Your Number1: 10 + 70 # Positional Arguments * def Full_name(First_name , Last_name) : * Complete_name = First_name +" "+ Last_name * print(Complete_name) * * Full_name("Jibran","Khan") + Output Is: + Jibran Khan + Second Example_(Positional Argument Mistake): * def Full_name(Last_name , First_name) : * Complete_name = First_name +" "+ Last_name * print(Complete_name) * * Full_name("Jibran","Khan") + Output Is: + Khan Jibran # Keyword Arguments * def Full_name(Last_name , First_name) : * Complete_name = First_name +" "+ Last_name * print(Complete_name) * * Full_name(First_name = "Jibran", Last_name = "Khan") + Output Is: + Jibran Khan # Theory Base Examples: * num_1 = 10 * num_2 = 5 * def addition(Ten , Five) : * Total = Ten - Five * print(Total) * addition(num_1, num_2) + Output Is: + 5 # Global Data & Local Data * First_num = 10 ===> This Is Global Scope Variable. * def theory(Ten , Tweenty = 20) : * Total = Ten + Tweenty * print(Total) * theory(First_num) + Output Is: + 30 + Second Example_(Default, Gloabl, Call Function) * Inst = "By myself" ===> Global Scope Variable. * def Course_detail(Inst , dur , lang = "Python Programming") : ===> Language Parameter Is a Default Value. * print(Inst +" "+ lang +" "+ dur) * Course_detail(Inst, dur = "1 Week") ===> Call the Function then Push Duration Argument Value. + Output Is: + By myself Python Programming 1 Week # ToDo AppliCation In Python * elements = [] * while True : * print("Element In Our List: ") * for element in elements : * print(" ===> " + element) * print("\n" + "Option: ") * print("1): Add Element.") * print("2): Delete Element.") * print("3): Delete All Element.") * print("4): Exit.") * print("Note: Please Give Input In Number e.g 1, 2, 3, 4") * inp = input("Enter Your Choice: ") * if inp == '1': * elements.append(input("Enter Your Item: ")) * elif inp == '2': * elements.remove(input("Enter Item To Delete: ")) * elif inp == '3': * elements.clear() * elif inp == '4': * break * else: * print("Invalid Syntex") * print("\n ------------------------------------------------------------------------------------------------------ \n") # OBJECT Oriented Programming Classes In Python # Classes - Template # OBJECT - Instance Of the Class # DRY - Do not repeat Yourself + Get_no_of_films(table) ===> Table Filmstar Is Not Exit. # Definition & Usage: + Python is an object oriented programming language. + Almost everything in Python is an object, with its properties and methods. + A Class is like an object constructor, or a "blueprint" for creating objects. + To create a class, use the keyword class: + Example: * class Student: * pass * Student_1 = Student() * Student_1.name = "Object Oriented Programming...!" * Student_1.Learner = "Jibran Abdul Jabbar" * print(Student_1.name) * print(Student_1.Learner) + Output Is: + Object Oriented Programming...! + Jibran Abdul Jabbar """ # !... Complete Python Programming With Definition With Explanation With Docs With Assignment With Coding & UsaGe ...! # !... Complete OBJECT OREINTED PROGRAMMING With Definition With Explanation With Docs With Coding & UsaGe ...!
dd5e97d2a15e472764a0fa3a160fb0d5b8484c5e
entrekid/algorithms
/basic/11652/counter.py
336
3.765625
4
from collections import Counter length = int(input()) num_list = [] for _ in range(length): num_list.append(int(input())) num_counter = Counter(num_list) max_num = max(num_counter.values()) key_list = [] for key, value in num_counter.items(): if value == max_num: key_list.append(key) key_list.sort() print(key_list[0])
00e15bf0e5f128afd98bc2f3865b3395fecb998c
anaCode26/PythonPractice
/Generadores.py
483
3.828125
4
# def generaPares(limite): # num=1 # miLista=[] # while num < limite: # miLista.append(num*2) # num = num + 1 # return miLista # print(generaPares(10)) #------------------------------------------------------ def devuelve_ciudades(*ciudades): for elemento in ciudades: yield elemento ciudades_devueltas = devuelve_ciudades("Madrid","Barcelona","Malaga","Alicante") print(next(ciudades_devueltas)) print(next(ciudades_devueltas))
b36554a96c28fbea1b75bd813b393c98f6c7865b
iamsabhoho/PythonProgramming
/Q1-3/MasteringFunctions/ReturnPosition.py
214
4.125
4
#Write a function that returns the elements on odd positions in a list. list = [1,2,3,4,5] def position(): for i in range(len(list)): if i%2 == 0: print(list[i]) return i position()
dc9d12cbfb40e0f1ed7ed91d4736e8fc433c9662
shivanigambhir11/SeleniumPython
/11javaScriptExecuterDemo.py
1,634
3.875
4
#JSE DOM can access any elemenrts on web page just like how selenium does # selenium have a method to execute javascript code in it # let's ee how to access elements with DOM and using selenium from selenium import webdriver driver = webdriver.Chrome(executable_path="/Users/shivanigambhir/Downloads/chromedriver 8.51.34 PM") driver.get("https://www.rahulshettyacademy.com/angularpractice/") driver.find_element_by_name("name").send_keys("Hello") # hello went into textbox print (driver.find_element_by_name("name").text) # i did not get the text i entered in text box "Hello", Whatever user enters # we cannot get that by this method print (driver.find_element_by_name("name").get_attribute("value")) # javascript method get attribute value will get the value, still # using bit of selenium - 1 way #Use javascript method to get value print (driver.execute_script('return document.getElementsByName("name")[0].value')) # pure javascrit > tested in console shopButton = driver.find_element_by_link_text("Shop") # In course he used CSS locator but i used driver.execute_script("arguments[0].click();",shopButton) # Two parameters, 2. locator/variable - what you target, 1. arguments- if teher # are 3 variable all will be soted in 1 i.i. why you have to give index and . action; driver.execute_script("window.scrollTo(0,document.body.scrollHeight);") # Vertical scroll from Top to bottom using Javascript, as selenium cannot scroll on pages
26d0aebf6591c146ef538f681b4ff244c136fd78
HarshithaKP/Python-practice-questions-
/18.py
948
4.15625
4
# Implement a program using CLA for simple arithmetic calculator exmaple: # operand operator operand ie. 10 + 10 / 30 * 20 import sys def addition(num1,num2): summ=num1+num2 print("Sum of two numbers is :",summ) def subtraction(num1,num2): subt=num1-num2 print("Sum of two numbers is :",subt) def multiplication(num1,num2): mul=num1*num2 print("Sum of two numbers is :",mul) def divisionion(num1,num2): div=num1/num2 print("Sum of two numbers is :",div) def main(): print("program using CLA for simple arithmetic calculator") try: num1=int(sys.argv[1]) num2=int(sys.argv[3]) operand=sys.argv[2] if(operand=='+'): addition(num1,num2) if(operand=='-'): subtraction(num1,num2) if(operand=='*'): multiplication(num1,num2) if(operand=='/'): division(num1,num2) except Exception as e: print("Usage <name.py> num1 operand num2 (operand:+,-,*,/)") finally: sys.exit() if __name__ == '__main__': main()
c8d39bd2b8edabc6cbba272cfac0122939b89231
williamgriffiths/Competitive-Programming
/Codeforces/472A. Design Tutorial - Learn from Math.py
322
3.921875
4
n = int(input()) def isPrime(num): for i in range(2,num): if num % i == 0: prime = False break else: prime = True return prime for i in range(n//2,3,-1): if isPrime(i) == False and isPrime(n-i) == False: print(i,n-i) break
a516b0167364bbc204e2e66b94c5b9cb1f276ad7
masotelof/AComp
/Tiempo/Recorrido_Listas.py
1,407
3.640625
4
import matplotlib.pyplot as plt from random import random from time import time if __name__ == "__main__": # número de ejecuciones iteraciones = 31 # número de iteraciones máximas max_elem = 1000000 # particiones par = 100 size = max_elem/par # Diferentes tamaños para probar num_elem = [ int(size*i) for i in range(1,par+1)] time_pos =[] time_it =[] time_fn =[] for tam in num_elem: # elementos con los que se van a probar elementos = [random() for _ in range(tam)] prom=0 for _ in range(iteraciones): tini = time() suma = 0 for i in range(len(elementos)): suma += elementos[i] tfin = time() prom += tfin-tini time_pos.append(prom/iteraciones) prom=0 for _ in range(iteraciones): tini = time() suma = 0 for elemento in elementos: suma += elemento tfin = time() prom += tfin-tini time_it.append(prom/iteraciones) prom=0 for _ in range(iteraciones): tini = time() suma = sum(elementos) tfin = time() prom += tfin-tini time_fn.append(prom/iteraciones) # graficamos los resultados plt.plot(num_elem, time_pos, label="Posición") plt.plot(num_elem, time_it, label="Iterador") plt.plot(num_elem, time_fn, label="Función") plt.title("Tiempo de Ejecución para la Suma de una Lista de Elementos") plt.xlabel("Número de Elementos") plt.ylabel("Tiempo") plt.legend(loc="upper left") plt.show()
349f786e233b1675675d96958b75acc5e4c6b80e
ajit-jadhav/CorePython
/1_Basics/7_ArraysInPython/a3_NumpyArray.py
1,042
4.34375
4
''' Created on 14-Jul-2019 @author: ajitj ''' ########################## Numpy Multi-dimensional array ################################3 ## Program 16 ## create simple array using numpy from numpy import * arr = array([10,20,30,40,50]) # create an array print(arr)#display array ## Program 20 ## create simple array using numpy linspace() from numpy import * #divide 0 to 10 into 5 parts and take those points into the array arr = linspace(0, 10, 5) print(arr)#display array ##Program 21 ## create simple array using numpy logspace() from numpy import * #divide the range: 10 power 1 to 10 power 5 into 5 equal parts arr = logspace(1, 4, 5) print(arr)#display array ## Program 22 ## create array with even numbers upto 10 from numpy import * arr = arange(2,11,2) # create an array print(arr)#display array ## Program 23 ## creating arrays using zeros() and ones() from numpy import * a = zeros(5,int) print(a)#display array b = ones(5)#default data type is float print(b)#display array
2eeadc9c237f1b5870cd782617cb4bb83e1bcf01
Aasthaengg/IBMdataset
/Python_codes/p02420/s222569418.py
208
3.515625
4
while True: d = input() if d == '-': break h = int(input()) rotate = 0 for i in range(h): rotate += int(input()) move = rotate % len(d) print(d[move:] + d[:move])
7d26553cd027f995ba64a537c54fb436442001fe
manufebie/cs-introduction-to-programming
/assigment_2/alice_n_bob.py
1,840
4.1875
4
import random import os, sys from random import shuffle # The Rules # 1) N stones forming a sequence labeled 1 to N. -> input N stones # 2) Alice and Bob take 2 cosecutive stones until there no consectutive stones left. # the number of the stone left determines the winner # 3) Alice plays first def clear_and_greet(): os.system('cls' if os.name == 'nt' else 'clear') print(''' ********************************************* **************** Alice N Bob **************** ************* A Game of Stones ************** ********************************************* ''') def start_game(): ''' For now, the game only creates a list that contains the number of stones inputted by the user. And then it checks if the last 'stone' in the list is odd. If odd Alice wins the game. It doesn't let Alice play first and let each player remove two stones each turn until there is no two stones to taken left. ''' clear_and_greet() # clears screen and shows game "logo" print('Enter number of stones:\n') # ask user for the sequence of stones n = int(input('> ')) clear_and_greet() # clears screen and shows game "logo" stones = list(range(1, n+1)) # create (list) sequence of stones shuffle(stones) # shuffle the sequence of stones to have them in a random order print('The stones are: {}\n'.format(stones)) if stones[-1] % 2 == 1: # Checks if the last stone in sequence is odd. If odd Alice wins. print('Last stone is {}. Alice wins!!!'.format(stones[-1])) else: print('The last stone is ({}). Bob wins!!!'.format(stones[-1])) while True: start_game() play_again = input('\nWould you like to play again? (Y/n): ') # ask if player wants to play again if play_again.lower() != 'n': continue else: sys.exit()
c4ddae55c811a631d19383cc4e66f5b6f8665c80
rmzturkmen/Python_assignments
/Assignment-14_1-Validate-brackets-combination.py
393
3.6875
4
# Validate-brackets-combination def check(data): cont = True while cont == True: cont = False for i in ["()", "{}", "[]"]: if i in data: cont = True data = data.replace(i, "") return len(data) == 0 print(check("()")) print(check("()[]()")) print(check("(]")) print(check("([)]")) print(check("{[]}")) print(check(""))
300c899359a1d4404ebc0af5cb163ba7046c7bdb
silverCore97/pytorch_test_examples
/show_results_gui_table.py
1,052
3.671875
4
import sqlite3 import sys, tkinter # ende function for getting rid of the GUI def ende(): main.destroy() # Verbindung, Cursor connection = sqlite3.connect("ML_data.db") cursor = connection.cursor() # SQL-Abfrage sql = "SELECT * FROM Data" # Kontrollausgabe der SQL-Abfrage # print(sql) # Absenden der SQL-Abfrage # Empfang des Ergebnisses cursor.execute(sql) # Create Tk object main = tkinter.Tk() list=["n","m","epoch","accuracy","time"] #Create top line of the table for i in range(len(list)): lb = tkinter.Label(main, text=str(list[i]), bg="#FFFFFF", bd=5, relief="sunken", anchor="e") lb.grid(row=0, column=i, sticky="we") #Rest of the table iterator=1 for dsatz in cursor: for i in range(len(list)): lb = tkinter.Label(main, text=str(round(dsatz[i],2)), bg="#FFFFFF", bd=5, relief="sunken", anchor="e") lb.grid(row=iterator, column=i, sticky="we") iterator +=1 # Verbindung beenden connection.close() main.mainloop()
9e57cd831b04115cd25922158bd1707dbaf9d1b1
lgc13/LucasCosta_portfolio
/python/practice/personal_practice/lpthw/e22_what_do_you_know_so_far.py
819
4.34375
4
# Learn Python the hard way # Exercise 22: What Do You Know So Far? print "LPTHW Practice" print "E22: What Do You Know So Far?" print "Done by Lucas Costa" print "Date: 01/26/2016" print "Message: you can use 'return' to return something from an equation" print "" random_thing = "variables" pointers_variable = "pointers" separate = "distinguish" them_variable = "them" print "I have learned that you can use: %s." % random_thing print "They name whatever you want. You can use these things: %s, %d, %r" print "Those ^ are are called: %s" % pointers_variable print "In case you want to print a symbol, just type it twice like this: \\" print "When using multiple pointers, use () to: %s %s" % (separate, them_variable) print "Printing many variables is easy: ", random_thing, pointers_variable, separate, them_variable
f4ff3482374f8c5375a265c465c6e3bfd9b4497d
fiftyfivebells/truck-delivery-optimizer
/ChainedHashTable.py
6,555
3.8125
4
# Stephen Bell: #001433854 import random as r # the number of bytes in an integer w = 32 class HashTable(object): def __init__(self): self.__initialize() # Initializes the internal structure. Sets the size of the hash table to 0, sets the dimension to # 1, gets the random number for hashing, and creates a backing array to store elements. def __initialize(self): self.size = 0 # number of items in the table self.dimension = 1 # dimension used by the hashing function self.seed = self.__random_odd_int() # seed used by the hashing function self.array = self.__allocate_backing_array(2 ** self.dimension) # backing array to hold lists of items # Inserts a new key/value pair into the table in O(1) amortized time. Each call to resize is O(n), but # resize should only be called occasionally. # # O(1) complexity (amortized) def insert(self, key, val): if self.size + 1 > len(self.array): self.__resize() # if the key already exists, get rid of it before inserting a new one if self.find(key) is not None: self.array[self.__hash(key)].remove((key, val)) self.array[self.__hash(key)].append((key, val)) self.size += 1 # Updates the value associated with the given key to the new value. Operates in O(1) time, since the # size of the array at each index in the backing array is very small (since the hashing function is good) # # O(1) complexity def update(self, key, val): self.find(key) hashed = self.__hash(key) for i in range(len(self.array[hashed])): if self.array[hashed][i][0] == key: self.array[hashed][i] = (key, val) # Removes the item with the specified key in amortized O(1) time. Each call to resize is O(n), but # reize should only be called occasionally, allowing the cost to be amortized. Returns None if the # key is not in the list. # # O(1) complexity (amortized) def remove(self, key): elements = self.array[self.__hash(key)] for x in elements: if x[0] == key: elements.remove(x) self.size -= 1 if 3 * self.size < len(self.array): self.__resize() return x return None # Finds and returns the value associated with the given key, or None if the key doesn't exist. This # is O(1) in practice, because even though we iterate the list at each index, the number of items in # the list is very small. # # O(1) complexity def find(self, key): for x in self.array[self.__hash(key)]: if x[0] == key: return x[1] return None # Allows use of bracket notation to get value associated with a certain key. Will raise an error # if the key does not exist # # O(1) complexity def __getitem__(self, key): return self.find(key) # Allows use of bracket notation to set a new value for the given key. Raises a KeyError if the key # does not exist in the backing array # # O(1) complexity (amortized) def __setitem__(self, key, val): self.insert(key, val) # O(n) time. Sets the dimension back to 1, creates a new backing array of size 2, and then sets the # number of items currently in the list back to 0 def clear(self): self.dimension = 1 self.array = self.__allocate_backing_array(2) self.size = 0 # Resizes the backing array of the hash table in O(n) time. First it determins the new dimension of the # hash table by finding the power of 2 that is less than or equal to the number of items in the table. # Then it creates a new array with that power of 2 empty spots. It then re-hashes all of the values in the # original backing array and puts them into the new array. # # O(n) complexity def __resize(self): self.dimension = 1 while (2 ** self.dimension) <= self.size: self.dimension += 1 self.size = 0 old_array = self.array self.array = self.__allocate_backing_array(2 ** self.dimension) for i in range(len(old_array)): for x in old_array[i]: self.insert(x[0], x[1]) # Generates a hash value in O(1) time. First it creates a hash from the given value by multiplying it by a # random 32 bit number, the getting the remainder of that divided by 2**32 (to throw away some of the bits), # then dividing by another large number to throw away more bits, creating a value that is within the size # of the backing array. The function is done again using the hashed value in place of the original value # to reduce collisions. # # O(1) complexity def __hash(self, val): return ((self.seed * hash(val)) % 2 ** w) // 2 ** (w - self.dimension) # Creates a new backing array in O(n) time. This simply takes in a size value, then creates a list of # size "size" with an empty list at each index. This is linear time because it goes from index 0 to # size - 1 putting empty lists at each point. # # O(n) complexity def __allocate_backing_array(self, size): return [[] for _ in range(size)] # Generates a random odd integer in O(1) time. This is constant because the randrange function creates # a random integer in constant time, and then a bitwise OR operation is done with 1 to ensure that the # last bit is a 1, ie. that the number is random. # # O(1) complexity def __random_odd_int(self): return r.randrange(2 ** w) | 1 # gets random int in range 1 - 2^32, then ORs it with 1 to make it odd # Allows users to iterate over the hash table with for loops. This is an O(n) time operation because it # touches every item in the list once in order to iterate everything it contains # # O(n) complexity def __iter__(self): for elements in self.array: for x in elements: yield x[0], x[1] # Checks whether the provided key is in the hash table. This is an O(1) operation, because even though it # is iterating the list contained at a certain index in the backing array, that list is guaranteed to be # small, so it is effectively constant time. # # O(1) complexity def __contains__(self, key): for element in self.array[self.__hash(key)]: if element[0] == key: return True return False
70af260ff5eaa180da241e2d920b5d05b66080c7
AmandaRH07/Entra21_Python
/01-Exercicios/Aula001/Ex2.py
1,265
4.15625
4
#--- Exercício 2 - Variáveis #--- Crie um menu para um sistema de cadastro de funcionários #--- O menu deve ser impresso com a função format() #--- As opções devem ser variáveis do tipo inteiro #--- As descrições das opções serão: #--- Cadastrar funcionário #--- Listar funcionários #--- Editar funcionário #--- Deletar funcionário #--- Sair #--- Além das opções o menu deve conter um cabeçalho e um rodapé #--- Entre o cabeçalho e o menu e entre o menu e o rodapé deverá ter espaçamento de 3 linhas #--- Deve ser utilizado os caracteres especiais de quebra de linha e de tabulação opcao = int(input(""" SISTEMA DE CADASTRO DE FUNCIONARIO\n\n\n {} - Cadastrar Funcionário {} - Listar Funcinários {} - Editar Funcionário {} - Deletar Funcionário {} - Sair\n\n\n Escolha uma opção: """.format(1,2,3,4,5))) if opcao == 1: print("A opção escolhida foi 'Cadastrar funcionário'") elif opcao == 2: print("A opção escolhida foi 'Listar funcionários'") elif opcao == 3: print("A opção escolhida foi 'Editar funcionário'") elif opcao == 4: print("A opção escolhida foi 'Deletar funcionário'") elif opcao == 5: print("A opção escolhida foi 'Sair'") else: pass
aeab1a7e08d12cfd4123c6f25c3d3fe2960c8ed0
WC2001/wdi
/wdi-1/8.py
172
3.546875
4
def pierwsza(x): i=2 if x==1: return False while i**2 <= x: if x%i == 0: return False i+=1 return True x=int(input()) print(pierwsza(x))
659d98f5d6c965399f3aa5a30f986775438b5229
Cosmo-Not/lesson1
/lesson_exception.py
492
3.546875
4
qa = {"Как дела?": "Хорошо!", "Что делаешь?": "Программирую"} def ask_user(): while True: try: dela = input("Как дела? ") if dela == 'Хорошо': break elif dela in dict.keys(qa): print(f'{qa[dela]}') else: print(f'Не понимаю :(') except (KeyboardInterrupt): print("\nПока!") break ask_user()
058e051fdea1480c3b46ce4352adc391eed9d386
wang-zhe-pro/pycharmcode
/双色球选号.py
1,307
3.859375
4
from random import randrange, randint, sample import random def display(balls): """ 按照题目所要求格式输出列表中的双色球号码 :param balls:双色球号码列表,如[9,12,16,20,30,33 3] :print:输出格式为09 12 16 20 30 33 | 03 :return: 无返回值 """ # 请在此处添加代码 # # *************begin************# s = [] for i in balls: if (i % 10 == i): s.append(str(i).zfill(2)) else: s.append(str(i)) for i in range(len(s)-1): print(s[i],end=" ") print("|",end=" ") print(s[-1],end=" ") print() # **************end*************# def random_select(): """ 随机选择一组号码 :return: 返回随机选择的这一组号码,如[9,12,16,20,30,33 3] """ # 请在此处添加代码 # # *************begin************# red=[x for x in range(1,34)] bule=[x for x in range(1,17)] red_ball=sample(red,6) bule_ball=sample(bule,1) red_ball.sort(); red_ball.append(bule_ball[0]) return red_ball # **************end*************# # n为注数 def main(n): for _ in range(n): display(random_select()) random.seed(3) n = int(input()) if __name__ == '__main__': main(n)
e2c0c801c620f80f614819787b90dbc0fdea79c2
devashish89/PluralsightPythonFundamentals
/ItertoolsLibrary.py
1,450
3.796875
4
import itertools # all - AND for list<bool> print(all([name == name.title() for name in ["London", "New York", "United States Of America"]])) #name.title() - all initial letters of words in upper case #any - OR for list<bool> print(any([x for x in range(10) if x%2==0])) # zip - merge lists horizontally mon = [10, 12, 14, 15, 21] tues = [11, 21, 18, 20, 21] wed = [22, 23, 20, 17, 21] for temp in zip(mon, tues, wed): print("max: {0:.3f}, min: {1:.3f}, avg: {2:.3f}".format(min(temp), max(temp), sum(temp)/len(temp))) print('.'*50) # chain - merge lists vertically into 1 list temperatures = itertools.chain(mon, tues, wed) print(temperatures) for temp in temperatures: print(temp) print("."*50) # count and islice """ import time x = itertools.count(1, 2) #Infinite loop starting from 1 and in step size of 2 (count backwards also using -1) while True: print(next(x)) time.sleep(2) print("-"*50) """ # islice to chunk/slice iterator for i in itertools.islice(itertools.count(1), 5): #print only first 5 values print(i) print("*"*50) for i in itertools.islice(itertools.count(10,-1), 5): #print only first 5 values print(i) print("*"*50) for i in itertools.islice(itertools.count(10,-1), 5, 10): #print values from 5th to 10th element print(i) print("*"*50) for i in itertools.islice(itertools.count(10,-1), 5, 10, 2): #print values from 5th to 10th element in step size=2 print(i)
0a70245a06312e49caa022dc9845d0f65cf74813
whoophee/DCP
/leetcode/LRU.py
1,526
3.59375
4
class Node: def __init__(self, key, val): self.key = key self.val = val self.next = None self.prev = None class LRU: def _use(self, key, val): cur = Node(key, val) if not self.ll_begin: self.ll_begin = self.ll_end = cur else: self.ll_end.next = cur cur.prev = self.ll_end self.ll_end = cur if key in self.map: tmp = self.map[key] cur_prev = tmp.prev cur_next = tmp.next if cur_prev: cur_prev.next = cur_next else: self.ll_begin = cur_next cur_next.prev = cur_prev elif len(self.map) == self.cap: tmp = self.ll_begin cur_next = tmp.next cur_next.prev = None self.ll_begin = cur_next self.map.pop(tmp.key) else: pass self.map[key] = cur def put(self, key, val): self._use(key, val) def get(self, key): cur = self.map.get(key) if cur: self._use(cur.key, cur.val) return cur.val else: return -1 def __init__(self, cap): self.cap = cap self.ll_begin = None self.ll_end = None self.map = {} #### cache = LRU(2) cache.put(1, 1) cache.put(2, 2) print(cache.get(1)) cache.put(3, 3) print(cache.get(2)) cache.put(4, 4) print(cache.get(1)) print(cache.get(3)) print(cache.get(4))
c99c4f855be21d2648f7453930267097ec634330
Jeep123Samuels/Codility_Lessons
/lesson_8/equi_leader.py
2,858
3.984375
4
"""Main script for equi_leader.py""" # A non-empty array A consisting of N integers is given. # # The leader of this array is the value that occurs in more than half of the elements of A. # # An equi leader is an index S such that 0 ≤ S < N − 1 and # two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value. # # For example, given array A such that: # # A[0] = 4 # A[1] = 3 # A[2] = 4 # A[3] = 4 # A[4] = 4 # A[5] = 2 # we can find two equi leaders: # # 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. # 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. # The goal is to count the number of equi leaders. # # Write a function: # # def solution(A) # # that, given a non-empty array A consisting of N integers, returns the number of equi leaders. # # For example, given: # # A[0] = 4 # A[1] = 3 # A[2] = 4 # A[3] = 4 # A[4] = 4 # A[5] = 2 # the function should return 2, as explained above. # # Assume that: # # N is an integer within the range [1..100,000]; # each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. # Complexity: # # expected worst-case time complexity is O(N); # expected worst-case space complexity is O(N) (not counting the storage required for input arguments). def solution(S): """Returns last index of the dominator or -1 if non exist.""" from collections import defaultdict def init_to_zero(): return 0 N = len(S) if N < 1: return -1 # create a queue with the first value in array. queue_ = [S[0]] last_index = 0 # Remember the count using pigeon hole with defaultdict. counting = defaultdict(init_to_zero) counting[S[0]] = 1 # Iterate through given array. # If current value in array not equal to the last added value, pop, # else we add the value to the tail of the queue. for i in range(1, N): counting[S[i]] += 1 if queue_ and S[i] != queue_[-1]: queue_.pop() else: queue_.append(S[i]) last_index = i if queue_ and counting[S[last_index]] > N//2: leader_count = counting[S[last_index]] else: return 0 eq_leader_count = 0 current_leader_count = 0 for i in range(N-1): # if value is the current leader. if S[i] == S[last_index]: current_leader_count += 1 if (current_leader_count > (i+1)//2 and (leader_count-current_leader_count) > (N-(i+1))//2): eq_leader_count += 1 return eq_leader_count if __name__ == "__main__": solution([4, 3, 4, 4, 4, 4, 2]) a = list() a.append('a') print(a) a.append('b') print(a) a.append('c') print(a)
cc0e5539384508e94cf01ee1886eeb971d263537
benedict-destiny/triangle-tracker
/triangle.py
793
4.0625
4
while True: print("welcome") A=int(input("enter the the value of side A")) B=int(input("enter the value of side B")) C=int(input("enter the value of side C")) if A==0 or B==0 or C==0: print("0 wacha ufala ushai ona 0 kwa triangle") elif A == B == C: print("the triangle is an equilateral triangle") elif A == B and A !=C: print("The triangle is an isocles triangle") elif B == C and B !=A: print("The triangle is an isocles triangle") elif C == A and C !=B: print("The triangle is an isocles triangle") elif A!=B and A!=C and B!=C: print("the triangle is an scalene triangle") else: print("that is not a triangle") try: pass except expression as identifier: pass finally: pass
5a8f30e46f1af69dfe4139bbdce1e3992acb0fe3
hnoskcaj/WOrk
/28.py
218
3.734375
4
i = [[1,2,3],[4,5,6],[7,8,9]] i[1][0] i = [0 for x in range(12)] print(i) j = [0]*12 print(j) i = [[0,0,0]for x in range(3)] print(i) i = [[0]*10 for x in range (10)] print(i) for x in range(len(i)): print(*i[x])
1c9e606feff5ecd06d0b00f893e7e1c6ca9e3fb4
MuhammadSuryono1997/task_python
/009.py
190
3.921875
4
usia = int(input("Masukkan usia : ")) if usia >= 21: print("DEWASA") elif usia >= 13: print("REMAJA") elif usia >= 9: print("BIMBINGAN ORANGTUA") elif usia < 9: print("SEMUA USIA")
dadec2ff51be09b5dd69f11547c44d99c9dbe223
Reidddddd/leetcode
/src/leetcode/python/PathSum_112.py
655
3.71875
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class PathSum_112(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ def path_sum(node, tmp, sum): if not node: return False tmp += node.val if not node.left and not node.right: return True if tmp == sum else False if path_sum(node.left, tmp, sum): return True return path_sum(node.right, tmp, sum) tmp = 0 return path_sum(root, 0, sum)
30446372af30aabcbcbccbd5219ce066d5476a9c
MrBearTW/TCFST
/Project/datacamp_study/Preprocessing.py
638
3.71875
4
# Import `datasets` from `sklearn` from sklearn import datasets # Load in the `digits` data digits = datasets.load_digits() # Print the `digits` data print(digits) # Import the `pandas` library as `pd` import pandas as pd # Load in the data with `read_csv()` digits = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tra", header=None) # Print out `digits` print(digits) # Get the keys of the `digits` data print(digits.keys()) # Print out the data print(digits.data) # Print out the target values print(digits.target) # Print out the description of the `digits` data print(digits.DESCR)
b941389af938cb871d26589d640b2e8bcb428fda
wzhy0576/ML
/ex/logicRegression/logicRegression.py
2,294
3.625
4
# -*- coding: utf-8 -*- #ML Andrew-Ng ex1 version1 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model def getData(data_frame): #DataFrame to Matrix data_frame.insert(0, 'Ones', 1) #insert in col 0 name Ones value 1 cols = data_frame.shape[1] #列数 X = data_frame.iloc[:,0:cols-1] #取前cols-1列,即输入向量 y = data_frame.iloc[:,cols-1:cols] #取最后一列,即目标向量 X = np.matrix(X.values) y = np.matrix(y.values) return [X, y] g = lambda x : 1 / (1 + np.exp(-x)) # 代价函数 J = lambda X, y, theta : np.sum(np.power((X * theta.T - y), 2)) / (2 * len(X)) # 经过一趟遍历,得到新的theta new_theta = lambda X, y, alpha, theta : theta - alpha * (g(X*theta.T) - y).T * X / len(X) def gradientDescent(X, y, alpha, times): theta = np.matrix([0, 0, 0]) #cost = np.zeros(times) for i in range(times): #cost[i] = J(X, y, theta) theta = new_theta(X, y, alpha, theta) return theta path = "./data1.txt" data = pd.read_csv(path, header=None, names=['exam1', 'exam2', 'admitted']) [X, y] = getData(data) final_theta = gradientDescent(X, y, 0.03, 1000) print(final_theta) positive = data[data.admitted.isin(['1'])] # 1 negetive = data[data.admitted.isin(['0'])] # 0 fig, ax = plt.subplots(figsize=(6,5)) ax.scatter(positive['exam1'], positive['exam2'], c='b', label='admitted') ax.scatter(negetive['exam1'], negetive['exam2'], s=50, c='r', marker='x', label='Not Admitted') # 设置图例显示在图的上方 box = ax.get_position() ax.set_position([box.x0, box.y0, box.width , box.height* 0.8]) ax.legend(loc='center left', bbox_to_anchor=(0.2, 1.12),ncol=3) # 设置横纵坐标名 ax.set_xlabel('Exam 1 Score') ax.set_ylabel('Exam 2 Score') plt.show() x1 = np.arange(130, step=0.1) x2 = -(final_theta[0][0] + x1*final_theta[0][1]) / final_theta[0][2] fig, ax = plt.subplots(figsize=(8,5)) ax.scatter(positive['exam1'], positive['exam2'], c='b', label='admitted') ax.scatter(negetive['exam1'], negetive['exam2'], s=50, c='r', marker='x', label='Not Admitted') ax.plot(x1, x2) ax.set_xlim(0, 130) ax.set_ylim(0, 130) ax.set_xlabel('x1') ax.set_ylabel('x2') ax.set_title('Decision Boundary') plt.show()
a76fa195501ec2696e2e7fe20724c605c093ff0f
chenpeikai/Rice_python
/1/guess_the_number.py
1,441
4.1875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console try: import simplegui except: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui import random # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global count frame = simplegui.create_frame("guess number" , 300 ,300) frame.add_button("range100" , range100) frame.add_button("range1000" , range1000) frame.add_input("input_guess" , input_guess , 100) # remove this when you add your code frame.start() # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game # remove this when you add your code global count count = random.randint(0,100) def range1000(): # button that changes the range to [0,1000) and starts a new game global count count = random.randint(0,1000) def input_guess(guess): # main game logic goes here guess_num = int(guess) if(count > guess_num): print("higher") elif(count < guess_num): print("lower") else: print("you are right") # remove this when you add your code # call new_game new_game() # always remember to check your completed program against the grading rubric
e3c96282cf434bf8922f9195864d7fc0e0777494
KariimAhmed/Machine-learning-AI
/Linear regression ( gradient descent and normal equation)/sol1_extra.py
3,227
3.890625
4
import matplotlib.pyplot as plt import numpy as np from gradientDescent import * from plotData import * from featureNormalize import * from normalEqn import * #plot data data = np.loadtxt('ex1data2.txt', delimiter=',', dtype=np.int64) X=data[:,0:2] y=data[:,2] m=y.size plt.ion() # turn on plotting interactive mode plt.figure(0) #create figure to plot into it #Plot 1 (Price vs size) plt.scatter(X[:,0],y,marker='x', color='r') plt.ylabel('House Prices') plt.xlabel('Size of house in ft^2') plt.show() #Plot 2 (Price vs no. of bedrooms) plt.figure(2) plt.scatter(X[:,1],y,marker='x', color='b') plt.ylabel('House Prices') plt.xlabel('No. of bedrooms') plt.show() X_un=X # un normalized X X_un = np.c_[np.ones(m), X_un] X, mu, sigma=feature_normalize(X) # V.I normailze X X = np.c_[np.ones(m), X] # Add a column of ones to X # Choose some alpha value alpha = 0.45# IF WE HAVE nan REDUCE alpha num_iters = 50 # also inc or dec to converge # Init theta and Run Gradient Descent theta = np.zeros(3) # 3 theta bec 2 features so theta0,theta1,theta2 theta1, J_history = gradient_descent_multi(X, y, theta, alpha, num_iters) J1=J_history #try different values for alpha alpha = 0.05 num_iters = 50 theta = np.zeros(3) theta2, J_history = gradient_descent_multi(X, y, theta, alpha, num_iters) J2=J_history #try different values for alpha alpha = 0.01 num_iters = 50 theta = np.zeros(3) theta3, J_history = gradient_descent_multi(X, y, theta, alpha, num_iters) J3=J_history # Plot the convergence graph plt.figure(3) plt.plot(np.arange(J_history.size), J1,c='r',label='J1=0.1') # NO. OF ITERATIONS VS CONST FUNCTION plt.plot(np.arange(J_history.size), J2,c='b',label='J2=0.05') plt.plot(np.arange(J_history.size), J3,c='y',label='J3=0.01') plt.legend() plt.xlabel('Number of iterations') plt.ylabel('Cost J') plt.show() # Display gradient descent's result print('Theta computed from gradient descent : \n{}'.format(theta)) # we will continue with J1 (the best convergence) #prediction # Predict values for a house with 1650 square feet and # 3 bedrooms. #h=theta0*X0+theta1*X1+theta2*X2 so its a dot product # in this example X1 is the space and X2 no of bedrooms and X0=1 #since theta is obtained by normalizing the features , so at prediction we have to # normalize X1 and X2 but Xo is kept the same because it's all ones price= 0 features= np.array([1650, 3]) features= (features-mu)/sigma features= np.r_[(1,features)] #(add one to the array) translates slice objects to concatenation along the first axis. price = np.dot(features, theta1) print('For house of area = 1650 ft^2 and 3 bedrooms , it costs about',price) # Normal euqation ( the exact solution if data is linear) # obtain theta using normal equation with no need to feature normalization and without # gradient descent ( works only for linear features) X = X_un # X agai will be the un normalized theta=normal_eqn(X, y) price= 0 features1= np.array([1,1650, 3]) price = np.dot(features1, theta) print('For house of area = 1650 ft^2 and 3 bedrooms , it costs using normal equation about',price) # so here the two prices are nearly the same after changing alpha to 0.45
2f6c43057eb53ec6f75c50a663e40ee217fe7c82
dom-0/python
/ohwell/global.py
197
3.578125
4
a = 1 b = 2 def fun(x, y): """global a global b""" a = x b = y print ("Within function a = {}, b = {}".format(a, b)) fun(10, 20) print ("Outside function a = {}, b = {}".format(a, b))
4c0615944bf0f5111f857e6a3f2a725ce55dba42
deep0892/Algorithms_Practice
/Leetcode/algorithms-questions/Plus_One.py
988
3.796875
4
# https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/559/ """ Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. """ from typing import List class Solution: def plusOne(self, digits: List[int]) -> List[int]: carry = 1 for i in reversed(range(len(digits))): digits[i] += carry carry = digits[i] // 10 digits[i] = digits[i] % 10 if carry: digits.insert(0, 1) return digits def main(): digits = [1,2,3] sol = Solution() print(sol.plusOne(digits)) digits = [4, 3, 2, 1] print(sol.plusOne(digits)) if __name__ == "__main__": main()
7abd67ef448d0e7f02ef63094cb1febc66663059
PhD-Strange/infa_2020_PhD_Strange
/lab2_1/turtle_9.py
369
3.90625
4
import turtle import numpy as np pi = np.pi turtle.shape('turtle') turtle.color('red') n = 3 r = 10 def angel(n, m): fi = 360/n while n > 0: turtle.left(fi) turtle.forward(m) n-=1 while n < 13: m = 2*r*np.sin(pi/n) x = (180 - 360/n)/2 turtle.left(x) angel(n, m) turtle.right(x) turtle.penup() turtle.forward(10) turtle.pendown() n+=1 r+=10
04f91300d880843407c0e1028dfa51b0e544dc07
saturnin13/poetry-generation
/src/RNN_pre_processing.py
1,823
3.796875
4
def extract_characters(shakespeare="shakespeare", combine=True): file = open("data/shakespeare.txt", "r") if shakespeare else open("data/spenser.txt", "r") if shakespeare == "shakespeare": poetry_list_by_line = shakespeare_extract_poetry_list(file) else: poetry_list_by_line = spencer_extract_poetry_list(file) for i in range(len(poetry_list_by_line)): poetry_list_by_line[i] = remove_leading_line_spaces(poetry_list_by_line[i]) # result = split_to_fixed_size_list(n_jump, poetry_list_by_line, size_input) result = poetry_list_by_line if combine: result = "\n\n".join(poetry_list_by_line) return result def split_to_fixed_size_list(n_jump, poetry_list_by_line, size_input): result = [] for poem in poetry_list_by_line: for i in range(int(len(poem) / n_jump)): curr_pos_start = i * n_jump if curr_pos_start + size_input >= len(poem): break result.append(poem[curr_pos_start:curr_pos_start + size_input]) return result def remove_leading_line_spaces(poem): while " " in poem: poem = poem.replace(" ", "") return poem def shakespeare_extract_poetry_list(file): text = file.read() poetry_list = text.lower().split("\n\n") for i in range(len(poetry_list)): start_line = 2 if i != 0 else 1 lines = poetry_list[i].split("\n") poetry_list[i] = '\n'.join(lines[start_line:]) return poetry_list def spencer_extract_poetry_list(file): text = file.read() poetry_list = text.lower().split("\n\n") for i in range(len(poetry_list) - 1, -1, -1): if i % 2 == 0: poetry_list.remove(poetry_list[i]) else: pass return poetry_list print(extract_characters(False, False))
6897d9a77ec7b617009a5b84a5ab00c61ac70192
jayeom-fitz/Algorithms
/CodeUp/Python기초낮은정답률/[기초5-2] 문자열/1754-큰 수 비교.py
759
3.703125
4
""" CodeUp 1754 : 큰 수 비교 https://www.codeup.kr/problem.php?id=1754 """ def swap(n1, n2): return [n2, n1] def comp1(n1, n2): if len(n1) > len(n2) : return True elif len(n1) < len(n2) : return False else : for i in range(len(n1)) : if ord(n1[i]) - ord(n2[i]) == 0 : continue elif ord(n1[i]) - ord(n2[i]) > 0 : return True else : return False def comp2(n1, n2): if n1[0] == '-' and n2[0] != '-' : return False elif n1[0] != '-' and n2[0] == '-' : return True elif n1[0] == '-' and n2[0] == '-' : return not comp1(n1[1:], n2[1:]) else : return comp1(n1, n2) n1, n2 = input().split() if comp2(n1, n2) : n = swap(n1, n2) n1 = n[0] n2 = n[1] print(n1, n2)
f11783d6d1a7830b4327802724b11441045297ac
leebyp/learn-python-the-hard-way
/ex41.py
863
3.828125
4
class : Tell Python to make a new kind of thing. object : Two meanings: the most basic kind of thing, and any instance of some thing. instance : What you get when you tell Python to create a class. def : How you define a function inside a class. self : Inside the functions in a class, self is a variable for the instance/object being accessed. inheritance : The concept that one class can inherit traits from another class, much like you and your parents. composition : The concept that a class can be composed of other classes as parts, much like how a car has wheels. attribute : A property classes have that are from composition and are usually variables. is-a : A phrase to say that something inherits from another, as in a "salmon" is-a "fish." has-a : A phrase to say that something is composed of other things or has a trait, as in "a salmon has-a mouth."
fc0a7766f626f88b13b3df993c327f2b18a34400
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/mhlsan022/question1.py
735
4.3125
4
'''This program checks whether a string is a palindrome or not Sandile Christopher Mahlangu 4 May 2014''' def palindrome(string): '''This function checks if a string is a palindrome or not using recursion''' if len (string)<=1:#if one word or no words are left in the string and it is a palindrome print this return True elif string[0]==string[len(string)-1]:#checking if the letter at the back is equal to the one infront return palindrome(string[1:len(string)-1]) else: return False if __name__=='__main__': string=input('Enter a string:\n') check=palindrome(string) if check: print('Palindrome!') else: print('Not a palindrome!')
05a5a1952e06c545ac79d35dd460c426b0fda1a2
behrouzmadahian/python
/TensorflowLearning/02-CNN.py
5,109
4.03125
4
''' A convolutional neural network using Tensorflow. Used data: MNIST database of handwrittern digits. ''' import tensorflow as tf # import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data", one_hot=True) # parameters learning_rate = 0.001 training_iters = 200000 batch_size = 128 display_step = 10 # network parameters n_inputs = 784 # MNIST data input image shape is 28x28=784 n_classes = 10 # MNIST data output classes are 10 (0-9 digits) dropout = 0.75 # dropout (probability of keeping units) # tf graph input x = tf.placeholder(tf.float32, [None, n_inputs]) y = tf.placeholder(tf.float32, [None, n_classes]) keep_prob = tf.placeholder(tf.float32) # dropout (keep probability) # create a wrapper for 2d convolutional network def conv2d(x, w, b, strides=1): # 2d convolutional neural network, with bias and ReLu activation # strides: the stride of the sliding window for each dimension x = tf.nn.conv2d(x, w, strides=[1, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) # create a wrapper for 2d max pooling def maxpool2d(x, k=2): # 2d max pool # kzise: size of the window for each dimension; # strides: the stride of the sliding window for each dimension return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # create convolutional model def conv_net(x, weights, biases, dropout): # reshape input x = tf.reshape(x, shape=[-1, 28, 28, 1]) # first convolutional layer conv1 = conv2d(x, weights['w1'], biases['b1']) # first max pooling layer conv1 = maxpool2d(conv1, k=2) # second convolutional layer conv2 = conv2d(conv1, weights['w2'], biases['b2']) # second max pooling layer conv2 = maxpool2d(conv2, k=2) # fully connected layer # reshape conv2 output to fit fully connected layer input fc = tf.reshape(conv2, [-1, weights['w_fc'].get_shape().as_list()[0]]) fc = tf.add(tf.matmul(fc, weights['w_fc']), biases['b_fc']) fc = tf.nn.relu(fc) # dropout fc = tf.nn.dropout(fc, dropout) # output class prediction out = tf.add(tf.matmul(fc, weights['out']), biases['out']) return out # store layers' weights and biases weights = \ { # 5x5 convolution (filter), 1 input channel, 32 outputs 'w1': tf.Variable(tf.random_normal([5, 5, 1, 32])), # 5x5 convolution (filter), 32 inputs, 64 outputs 'w2': tf.Variable(tf.random_normal([5, 5, 32, 64])), # fully connected 7*7*64 inputs (max pool k=2 with SAME padding makes a 7x7 filters after two layers), # 1024 outputs 'w_fc': tf.Variable(tf.random_normal([7 * 7 * 64, 1024])), # 1024 inputs, 10 outputs (class prediction) 'out': tf.Variable(tf.random_normal([1024, n_classes])) } ''' a better practice for defining W is as follows: def weights_variable(shape): initial = tf.truncated_random(shape, stddev=0.1) return tf.Variable(initial) # a better practice for defining bias is as follows: def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) ''' biases =\ { 'b1': tf.Variable(tf.random_normal([32])), 'b2': tf.Variable(tf.random_normal([64])), 'b_fc': tf.Variable(tf.random_normal([1024])), 'out': tf.Variable(tf.random_normal([n_classes])) } # prediction model pred = conv_net(x, weights, biases, keep_prob) # cost and optimization cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # evaluate model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # initialize variables init = tf.global_variables_initializer() # launch default graph with tf.Session() as session: session.run(init) step = 1 # training cycle while step * batch_size < training_iters: x_batch, y_batch = mnist.train.next_batch(batch_size) # run optimization session.run(optimizer, feed_dict={x: x_batch, y: y_batch, keep_prob: dropout}) if step % display_step == 0: batch_cost, batch_accuracy = session.run([cost, accuracy], feed_dict={x: x_batch, y: y_batch, keep_prob: 1.0}) print("Iteration:", (step * batch_size), "Batch cost=", batch_cost, "Training accuracy=", batch_accuracy) step += 1 print("Optimization finished!") # test model with test data (for 256 images) print("Testing accuracy=", session.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.0}))
8cdb41ba9e17ac65fe9d496c02831ed3c663585f
anthonysim/Python
/Intro_to_Programming_Python/cowboyOrder.py
1,290
3.75
4
""" Cowboy Order 1) Create a file with the list '3', '2', '10', '1', '4' named Orders.txt. 2) Take the list of items in Cowboy.txt and calculate the list of items purchased and calculate how much each item will cost plus the grand total. Use Cowboy.txt """ def main(): file = "Cowboy.txt" cowboy = getData(file) outfile = open("Orders.txt", 'w') orders = createFile(outfile) order(cowboy, orders) def getData(file): infile = open(file, 'r') cowboy = [line.rstrip().split(',') for line in infile] infile.close() for i in range(len(cowboy)): cowboy[i][1] = eval(cowboy[i][1]) return cowboy def createFile(outfile): orderAmts = ['3', '2', '10', '1', '4'] for i in range(len(orderAmts)): orderAmts[i] = orderAmts[i] + "\n" outfile.writelines(orderAmts) outfile.close() infile = open("Orders.txt", 'r') orders = [line.rstrip() for line in infile] infile.close() for i in range(len(orders)): orders[i] = eval(orders[i]) return orders def order(cowboy, orders): total = 0 for i in range(5): print(str(orders[i]) + " " + str(cowboy[i][0]) + ": ", end='') print("${0:,.2f}".format(orders[i] * cowboy[i][1])) total += (orders[i] * cowboy[i][1]) print("TOTAL: ${0:,.2f}".format(total)) main()
125688b9ae21ad67561c0bc76d918bffdd121d45
testowy4u/L_Python_Lutz_Learning-Python_Edition-5
/Part 2/Lutz_Ch_05.py
14,520
4.21875
4
__author__ = 'Rolando' ############################################ #### Part 2: Types and Operations PG 90-315 ### CH 5: Numeric Types PG 133 ############################################ print(40 + 3.14) # Integer to float, float math/result print(int(3.1415)) # Truncates float to integer print(float(3)) # Converts integer to float a = 3 b = 4 print(a + 1, a - 1) # Addition (3 + 1), subtraction (3 - 1) print(b * 3, b / 2) # Multiplication (4 * 3), division (4 / 2) print(a % 2, b ** 2) # Modulus (remainder), power(4 ** 2) print(2 + 4.0, 2.0 ** b) # Mixed type conversions print(b / 2 + a) print(b / (2.0 + a)) print(1 / 2.0) num = 1 / 3.0 print(num) print("%e" % num) # String formatting expression print("%4.2f" % num) # Alternate floating point expression print("{0:4.2f}".format(num)) # String formatting method: Python 2.6, 3.0, and later print(repr("spam")) print("spam") print(1 < 2) # Less than print(2.0 >= 1) # Greater than or equal print(2.0 == 2.0) # Equal value print(2.0 != 2.0) # Not Equal value X, Y, Z, = 2, 4, 6 print(X < Y < Z) # Chained comparisons, range test print(X < Y > Z) print(1 < 2 < 3.0 < 4) print(1 > 2 > 3.0 > 4) print(1 == 2 < 3) # Same as 1 == 2 and 2 < 3, eval to False print(False < 2) # Means 0 < 3, which is True print(1.1 + 2.2 == 3.3) print(1.1 + 2.2) print(int(1.1 + 2.2) == int(3.3)) print(10 / 4) print(10 / 4.0) print(10 // 4) print(10 // 4.0) import math print(math.floor(2.5)) # Closest number below value print(math.floor(-2.5)) print(math.trunc(2.5)) # Truncate fractional part(toward zero) print(math.trunc(-2.5)) print(5 / 2, 5 / -2) print(5 // 2, 5 // -2) print(5 / 2.0, 5 / -2.0) print(5 // 2.0, 5 // -2.0) print(5 / -2) # keep remainder print(5 // -2) # Floor blow result print(math.trunc(5 / -2)) # Truncate instead of floor print((5 / 2), (5 / 2.0), (5 / -2.0), (5 / -2)) print((5 // 2), (5 // 2.0), (5 // -2.0), (5 // -2)) print((9 / 3), (9.0 / 3), (9 // 3), (9 // 3.0)) print(1j * 1J) print(2 + 1j * 3) print((2 + 1j) * 3) ## PG 151 Hex, Octal, Binary: Literals and conversions print(0o1, 0o20, 0o377) # Octal literals: Base 8, digits 0-7 print(0x01, 0x10, 0xFF) # Hex literals: Base 16, digits 0-9/A-F print(0b1, 0b10000, 0b11111111) # Binary literals: Base 2, digits 0-1 print(0xFF, (15 * (16 ** 1)) + (15 * (16 ** 0))) # How hex/binary map to decimal print(0x2F, (2 * (16 ** 1)) + (15 * (16 ** 0))) print(0xF, 0b1111, (1 * (2 ** 3) + 1 * (2 ** 2) + 1 * (2 ** 1) + 1 * (2 ** 0))) print(oct(64), hex(64), bin(64)) # Numbers -> digit strings print(64, 0o100, 0x40, 0b1000000) print(int('64'), int('100', 8), int('40', 16), int('1000000', 2)) print(int('0x40', 16), int('0b1000000', 2)) print(eval('64'), eval('0o100'), eval('0x40'), eval('0b1000000')) print('{0:o}, {1:x}, {2:b}'.format(64, 64, 64)) print('%o, %x, %x. %X' % (64, 64, 255, 255)) print(0o1, 0o20, 0o377) x = 1 # 1 decimal is 0001 in bits print(x << 2) # Shift left 2 bits: 0100 print(x | 2) # Bitwise OR (either bit=1): 0011 print(x & 1) # Bitwise AND (both bits=1: 0001 X = 0b0001 # Binary literals print(X << 2) # Shift left print(bin(X << 2)) # Binary digits string print(bin(X | 0b010)) # Bitwise OR: either print(bin(X & 0b1)) # Bitwise AND: both X = 0xFF # Hex literals print(bin(X)) print(X ^ 0b10101010) # Bitwise XOR: either but not both print(bin(X ^ 0b10101010)) print(int('01010101', 2)) # Digits=>number: string to int per base print(hex(85)) # Number=>digits: Hex digit string X = 99 print(bin(X), X.bit_length(), len(bin(X)) - 2) # print(bin(256), (256).bit_length(), len(bin(256) - 2)) import math print(math.pi, math.e) # Common constants print(math.sin(2 * math.pi / 180)) # Sine, tangent, cosine print(math.sqrt(144), math.sqrt(2)) # Square root print(pow(2, 4), 2 ** 4, 2.0 ** 4.0) # Exponential power print(abs(-42.0), sum((1, 2, 3, 4))) # Absolute value, summation print(min(3, 1, 2, 4), max(3, 1, 2, 4)) # Minimum, Maximum print(math.floor(2.567), math.floor(-2.567)) # Floor (next-lower integer) print(math.trunc(2.567), math.trunc(-2.567)) # Truncate (drop decimal digits) print(int(2.567), int(-2.567)) # Truncate (integer conversion) print(round(2.567), round(2.467), round(2.567, 2)) # Round print('%.1f' % 2.567, '{0:.2f}'.format(2.567)) # Round for display print((1 / 3.0), round(1 / 3.0, 2), ('%.2f' % (1 / 3.0))) print(math.sqrt(144)) # Module print(144 ** .5) # expression print(pow(144, .5)) # Built-in print(math.sqrt(1234567890)) # Larger numbers import random print(random.random()) # Random floats, integers, choices, shuffles print(random.random()) print(random.randint(1, 10)) print(random.randint(1, 10)) print(random.choice(['Life of Brian', 'Holy Grail', 'Meaning of life'])) print(random.choice(['Life of Brian', 'Holy Grail', 'Meaning of life'])) suits = ['hearts', 'clubs', 'diamonds', 'spades'] random.shuffle(suits) print(suits) random.shuffle(suits) print(['clubs', 'diamonds', 'hearts', 'spades']) ## PG 157 Decimals print(0.1 + 0.1 + 0.1 - 0.3) from decimal import Decimal print(Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')) print(Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.30')) import decimal print(decimal.Decimal(1) / decimal.Decimal(7)) # Default: 28 digits decimal.getcontext().prec = 4 print(decimal.Decimal(1) / decimal.Decimal(7)) # Fixed precision print(Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3)) print(1999 + 1.33) # This has more digits in memory than displayed decimal.getcontext().prec = 2 pay = decimal.Decimal(str(1999 + 1.33)) print(pay) decimal.getcontext().prec = 28 print(decimal.Decimal('1.00') / decimal.Decimal('3.00')) with decimal.localcontext() as ctx: ctx.prec = 2 print(decimal.Decimal('1.00') / decimal.Decimal('3.00')) print(decimal.Decimal('1.00') / decimal.Decimal('3.00')) ## PG 160 fractions from fractions import Fraction x = Fraction(1, 3) # Numerator, Denominator y = Fraction(4, 6) # Simplified to 2, 3 by gcd print(x) print(y) print(x + y) # results are exact numerator, denominator print(x - y) print(x * y) print(Fraction('.25')) print(Fraction('1.25')) print(Fraction('.25') + Fraction('1.25')) a = 1 / 3.0 # Only as accurate as floating-point hardware b = 4 / 6.0 # Can lose precision over many calculations print(a) print(b) print(a + b) print(a - b) print(a * b) print(0.1 + 0.1 + 0.1 - 0.3) # Should be zero, close but no exact print(Fraction(1, 10) + Fraction(1, 10) + Fraction(1, 10) - Fraction(3, 10)) print(Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')) print(1 / 3) print(Fraction(1, 3)) decimal.getcontext().prec = 2 print(Decimal(1) / Decimal(3)) print((1 / 3) + (6 / 12)) print(Fraction(6, 12)) print(Fraction(1, 3) + Fraction(6, 12)) print(decimal.Decimal(str(1 / 3)) + decimal.Decimal(str(6 / 12))) print(1000.0 / 1234567890) print(Fraction(1000, 1234567890)) print(2.5.as_integer_ratio()) # Float object method f = 2.5 z = Fraction(*f.as_integer_ratio()) # Convert float->fraction: two args print(z) # Same as Fraction(5, 2) print(x) print(x + z) print(float(x)) print(float(z)) print(float(x + z)) print(17 / 6) print(Fraction.from_float(1.75)) # Convert float -> fraction: other way print(Fraction(*1.75.as_integer_ratio())) print(x) print(x + 2) # Fraction + int -> Fraction print(x + 2.0) # Fraction + float -> Float print(x + (1. / 3)) # Fraction + float -> Float print(x + (4. / 3)) print(x + Fraction(4, 3)) # Fraction + Fraction -> Fraction print(4.0 / 3) # print(4.0 / 3).as_integer_ratio() # print(x) # a = x + Fraction(*(4.0 / 3).as_integer_ratio()) # print(a) # print(a.limit_denominator(10)) ## PG 163 Sets x = set('abcde') y = set('bdxyz') print(x) print(y) print(x - y) # Difference print(x | y) # Union print(x & y) # Intersection print(x ^ y) # Symmetric difference print(x > y, x < y) # Superset, subset print('e' in x) # Membership print('e' in 'Camelot', 22 in [11, 22, 33]) # Works with other types as well z = x.intersection(y) # Same as x & y print(z) z.add('SPAM') # Insert one item print(z) z.update({'X', 'Y'}) # Merge: in-place union print(z) z.remove('b') # Delete one item print(z) for item in set('abc'): print(item * 3) S = set([1, 2, 3]) print(S | set([3, 4])) # Expressions require both to be sets # print(S | [3, 4]) print(S.union([3, 4])) # But their methods allow any iterable print(S.intersection((1, 3, 5))) print(S.issubset(range(-5, 5))) print(set([1, 2, 3, 4])) # Built-in: same as in 2.6 print(set('spam')) # Add all items in an iterable print({1, 2, 3, 4}) # Set literals: new in 3.X (and 2.7) S = {'s', 'p', 'a', 'm'} S.add('alot') # Methods work as before print(S) S1 = {1, 2, 3, 4} print(S1 & {1, 3}) # Intersection print({1, 5, 3, 6} | S1) # Union print(S1 - {1, 3, 4}) # Difference print(S1 > {1, 3}) # Superset print(S1 - {1, 2, 3, 4}) # Empty sets print differently print(type({})) # Because {} is an empty dictionary S = set() # Initialize an empty set S.add(1.23) print(S) print({1, 2, 3} | {3, 4}) # print({1, 2, 3} | [3, 4]) print({1, 2, 3}.union([3, 4])) print({1, 2, 3}.union({3, 4})) print({1, 2, 3}.union(set([3, 4]))) print({1, 2, 3}.intersection((1, 3, 5))) print({1, 2, 3}.issubset(range(-5, 5))) print(S) # S.add([1, 2, 3]) # Only immutable objects work in a set S.add((1, 2, 3)) # NO list or dict, but tuple OK print(S | {(4, 5, 6), (1, 2, 3)}) print((1, 2, 3) in S) print((1, 4, 3) in S) print((4, 5, 6) in S) print({x ** 2 for x in [1, 2, 3, 4]}) # 3.X/2.7 set comprehension print({x for x in 'spam'}) # Same as: set('spam') print({c * 4 for c in 'spam'}) # Set of collected expression results print({c * 4 for c in 'spamham'}) S = {c * 4 for c in 'spam'} print(S | {'mmmm', 'xxxx'}) print(S & {'mmmm', 'xxxx'}) L = [1, 2, 1, 3, 2, 4, 5] print(set(L)) L = list(set(L)) # Remove duplicates print(L) print(list(set(['yy', 'cc', 'aa', 'xx', 'dd', 'aa']))) # But the order may change print(set([1, 3, 5, 7]) - set([1, 2, 4, 5, 6])) print(set('abcdefg') - set('abdghih')) print(set('spam') - set(['h', 'a', 'm'])) print(set(dir(bytes)) - set(dir(bytearray))) print(set(dir(bytearray)) - set(dir(bytes))) L1, L2 = [1, 3, 5, 2, 4], [2, 5, 3, 4, 1] print(L1 == L2) # Order matters in sequences print(set(L1) == set(L2)) # Order-neural equality print(sorted(L1) == sorted(L2)) # Similar but results ordered engineers = {'bob', 'sue', 'ann', 'vic'} managers = {'tom', 'sue'} print('bob' in engineers) # Is bob an engineer? print(engineers & managers) # Who is both engineer and manager? print(engineers | managers) # All people in either category print(engineers - managers) # Engineers who are not managers print(managers - engineers) # Managers who are no engineers print(engineers > managers) # Are all managers engineers? (superset) ### PG 171 Booleans print(type(True)) print(isinstance(True, int)) print(True == 1) # Same value print(True is 1) # but a different object: see the next chapter print(True or False) # Same as: 1 or 2 print(True + 4) ## Test your knowledge ### 1 What is the value of the expression 2 * (3 + 4) in python? """ 14 """ ### 2. What is the value of the expression 2 * 3 + 4 in python? """ 10 """ ### 3. What is the value of the expression 2 + 3 * 4 in python? """ 14 """ ### 4. What tools can you use to find a number's square root, as well as its square? """ Functions for obtaining the square root, as well as pi, tangents, and more, are available in the imported math module. To fin a number's square, use either the exponent expression X ** w or the built-in function pow(X, 2). Either of theses last two can also compute the square root when a power of 0.5 (e.g., X ** .5). """ ### 5. What is the type of the result of the expression 1 + 2.0 + 3? """ The result will be a floating-point number: the integers are converted up to floating point, the most comp;ex type in the expression, and floating-point math is used to evaluate it. """ ### 6. How can you truncate and round a floating-point number? """ The int(N) and math.trunc(N) functions truncate, and the round(N, digits) function rounds We can also compute the floor with math.floor(N) and reound for display with string formatting operations. """ ### 7. How can you convert an integer to a floating-point number? """ The float(I) function converts an integer to a floating point, mixing an integer with a floating-point within an expression will result in a conversion as well. In some sense, Python 3.X / division converts too-- it always returns a floating-point result that includes the remainder, even if both operands are integers. """ ### 8. How would you display an integer in octal, hexadecimal, or binary notation? """ The oct(I) and hex(I) built-in functions return the octal and hexadeciml string forms for an integer. The bin(I) call also returns a number's binary digits string in Pythons 2.6, 3.0, and later. The % string formatting expresion and format string method also provide targets for such conversions. """ ### 9. How might you convert an octal, hexadecimal, o binary string to a plain integer? """ The int(S, base) function can be used to convert from octal and hexadecimal strings to normal integers (pass in 8, 16, or 2 for the base). The eval(S) function can be used for this purpose too, but it's more expensive to run and can have security issues. Note that integers are always stored in binary form in computer memory, these are just display string format conversions. """
bd62daffc5ee886f2fd2fb215c2a9ffa89d36b72
MacHu-GWU/pyrabbit-python-advance-guide-project
/pyguide/p3_stdlib/c08_datatypes/collections/ordereddict.py
1,459
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Reference: https://docs.python.org/3.3/library/collections.html#collections.OrderedDict """ from __future__ import print_function from collections import OrderedDict import random import sys def maintain_the_order(): """ordered dict iterate items by the order the key originally inserted """ d = dict() d["A"] = 3 d["B"] = 2 d["C"] = 1 od = OrderedDict() od["A"] = 3 od["B"] = 2 od["C"] = 1 print("{:=^100}".format("key order in regular dict is random")) for k in d: print(k) print("{:=^100}".format("key order in ordered dict " "is the order key been inserted")) for k in od: print(k) def memory_efficiency(): """比较 ``dict`` 和 ``OrderedDict`` 的内存开销。 结论: 在Python2中, 使用 ``sys.getsizeof`` 得到的开销大小是一样的。但是这是因为 ``sys.getsizeof`` 的实现机制导致的。实际的内存开销是一定会大于普通的 ``dict``. 这一点在Python3中得以被正确地显示。 """ d1 = {random.randint(1, 1000): random.randint(1, 1000) for i in range(1000)} od1 = OrderedDict() for k, v in d1.items(): od1[k] = v print("dict in memroy: %s" % sys.getsizeof(d1)) print("OrderedDict in memroy: %s" % sys.getsizeof(od1)) if __name__ == "__main__": maintain_the_order() memory_efficiency()
15c4796472646a05c53a7ded01fc8c9845a728a5
810Teams/pre-programming-2018-solutions
/Onsite/1160-Juggling The Ball.py
1,204
3.625
4
""" Pre-Programming 61 Solution By Teerapat Kraisrisirikul """ def main(): """ Main function """ data = {'FOOT': 5, 'LEG': 10, 'HEAD': 15, 'DOWN': 0, 'END LEAW GUN': 0} acts = list() score, down, passed, passed_scr = 0, 0, False, 100 while down < 3: acts.append(input().upper()) if acts[-1] in data: score += data[acts[-1]] if acts[-1] == 'DOWN': if score >= passed_scr: passed, passed_scr = True, score score = 0 down += 1 continue if len(acts) >= 2 and acts[-2] == 'FOOT' and acts[-1] == 'HEAD': score += 2 if len(acts) >= 2 and acts[-2] == 'LEG' and acts[-1] == 'HEAD': score += 3 if len(acts) >= 3 and acts[-3] == 'FOOT' and acts[-2] == 'LEG' and acts[-1] == 'HEAD': score += 15 if len(acts) >= 2 and acts[-2] == 'HEAD' and acts[-1] == 'FOOT': score -= 10 if acts[-1] == 'END LEAW GUN': break if score >= passed_scr: passed, passed_scr = True, score if passed: print('P\'GUNGUN can pass and score is', passed_scr) else: print('P\'GUNGUN Not pass') main()
bd858ca8d02a0ac748b70794eb6ead5ba8260a34
joshpaulchan/bayes-spam-filter
/sfilt.py
3,679
3.578125
4
#! /usr/bin/env python3 # Joshua Paul A. Chan # This is an exercise in understanding and implementing the Bayes Theorem as a spam filter. import string class Message(object): def __init__(self, email_to, email_from, body): self.email_to = email_to self.email_from = email_from self.body = body def get_recipients(self): return self.email_to def get_sender(self): return self.email_from def get_body(self): return self.body def __str__(self): # 40 is about less than half an average sentence # 5.1 + 1 avg char length per word + whitespace # 14 words per sentence on avg return "<Message '{}..'>".format(self.body[:40]) def __repr__(self): return str(self) class SpamFilter(object): # Build a SpamFilter from a model @classmethod def load_model(cls, fname): sf = cls() f = open(fname, 'r') for line in f: w, p_s, p_n = line.split(',') sf.set_word(w, float(p_s), float(p_n)) return sf def save_model(self, fname): f = open(fname, 'w+') for word, p in self.words: f.write('{},{},{}\n'.format(word, p[0], p[1])) def __init__(self): self.words = { # 'i': [0.5, 0.5], 'rolex': [ 0.0125, 0.005], 'stock': [ 0.2, 0.06], 'undervalued': [0.1, 0.025] } def set_word(self, w, p_spam, p_not): self.words[w] = [p_spam, p_not] def tokenize_words(self, text): return map(lambda w: w.strip(' ').strip(string.punctuation).lower(), text.split(' ')) def train(self, message, result): # TODO pass # determines if given message is spam # @param: message:<Message> # @returns boolean def is_spam(self, msg): print(msg) # tokenize body words = self.tokenize_words(msg.body) # print(words) P_spam = 0 P_notspam = 0 for word in words: probs = self.words.get(word) # print(probs) if probs != None: P_spam = P_spam*probs[0] P_notspam = P_notspam*probs[1] if P_spam == 0: P_spam = probs[0] if P_notspam == 0: P_notspam = probs[1] # print(P_spam) # print(P_notspam) if (P_spam + P_notspam) == 0: return 0 return (P_spam)/(P_spam + P_notspam) # TRAINING SETS # non-spam B = [ Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL'), Message('me', 'you', 'LOLOLOLOL') ] G = [ Message('me', 'you', 'Hey I have this rolex that you might like.'), Message('me', 'you', 'What are you doing for lunch tmm?'), Message('me', 'you', 'Hello') ] # Parses CLI flags and commands # @param filename # @returns <Tuple(<Float>,<String>)> def main(): f = SpamFilter.load_model('model.txt') # Train model # Parse filename # Read file # Predict for message in G: confidence = f.is_spam(message) print("{:.2%} probability that this is spam.\n".format(confidence)) # Report if __name__ == '__main__': main()
afb6f9186d50ff22c384d49e2f06c4a2e18b12b1
MattyHB/Python
/EarlyPython/LargerThan50.py
197
4.03125
4
x = 50 y = int(input("Insert Number: ")) if x > y: print("Number is smaller than 50") else: if x ==y: print("Your number is 50") else: print("Number is larger than 50")
e7822cb1ddd920b3fe7d894edc617741180c461f
Anseik/algorithm
/0826_stack/stack3.py
298
3.890625
4
stack = [] stack.append(1) # push stack.append(2) stack.append(3) print(stack) if stack: # len(stack) != 0 # 비어있지 않은지 항상 확인하자!! print(stack.pop()) if stack: # len(stack) != 0 print(stack.pop()) if stack: # len(stack) != 0 print(stack.pop()) print(stack)
e168d6f8c805065bf6291959521ef617c24b8a70
fangzhou/algorithm-practice
/depth_first_search/unique_permutations.py
2,443
3.546875
4
import logging import sys import unittest """ Problem: Given a list of integers, generate all unique permutation series from these integers. The input list may have duplicated numbers. """ def permuter(results, nums, prefix, log): """ DFS based permuter: Args: results: result output list nums: sorted input array prefix: generated prefix for permutation string, notice we are storing index for numbers in input, not the numbers Returns: None, results being appended to results list """ if len(prefix) == len(nums): # All numbers in input have been used, convern index to number # and add to result results.append([nums[p] for p in prefix]) return else: for i in xrange(len(nums)): if i in prefix: # if number at position i already used continue elif i > 0 and nums[i] == nums[i-1] and i-1 not in prefix: # for duplicated number, always picking the first occurrence continue else: # Recursively adding new results by appending the prefix log.debug(len(prefix)*" " + str(prefix)) log.debug(len(prefix)*" " + "current index: {0}:{1}, prev: " "{2}:{3}".format(i, nums[i], i-1, nums[i-1])) permuter(results, nums, prefix + [i], log) def permute(nums, log=None): if log is None: log = logging.getLogger(sys._getframe().f_code.co_name) log.setLevel(logging.DEBUG) results = [] sorted_nums = sorted(nums) permuter(results, sorted_nums, [], log) return results class testPermuter(unittest.TestCase): def setUp(self): logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger("ShortestSubarray") def test_1(self): A = [1,1,2] print "Test 1:\nInput: {0}".format(str(A)) result = permute(A) print "Result: {0}".format(str(result)) def test_2(self): A = [-1,2,-1,2,1,-1,2,1] print "Test 2:\nInput: {0}".format(str(A)) result = permute(A, self.logger) print "Result: {0}".format(str(result)) def test_3(self): A = [2,2,3,3,3] print "Test 3:\nInput: {0}".format(str(A)) result = permute(A, self.logger) print "Result: {0}".format(str(result)) if __name__ == "__main__": unittest.main()
ea8c0e6213edcfd23dec292e42ad38670aab2fbc
thenavdeeprathore/LearnPython3
/Programs/List_Programs/FindListLength.py
376
4.40625
4
# Various ways to find length of the list # 1 test_list = [1, 4, 5, 7, 8] # Printing test_list print("The list is : ", test_list) counter = 0 for i in test_list: # incrementing counter counter = counter + 1 # Printing length of list print("Length of list using naive method is : " + str(counter)) # 2 print("Length of list using len function : ", len(test_list))
c38b4483ec11bd523f7f6e771f4e830b08a28b0d
kamilpierudzki/User-Activity-Classification-Model
/plot_util.py
951
3.53125
4
import matplotlib.pyplot as plt def show_accuracy(history): acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validating accuracy') plt.title('Training and validating accuracy') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() def show_loss(history): loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validating loss') plt.title('Training and validating loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() def print_loss_acc(loss, acc): print('accuracy: {:5.2f}%'.format(100 * acc)) print('loss: {:5.2f}%'.format(100 * loss))
b8b6408914fd0d243fd880ad0c3339f442dd8716
OneCleverDude/shatteredgalaxies
/initialstargeneration.py
10,351
3.53125
4
# # StarSystem Creation # Python 3 project # First python coding attempt # import random import json def spectralclass(argument): # Updated to the table in the VBAM Galaxies Google Doc spectralclass = { 2: "Class O Extremely Bright Blue", 3: "Class B Bright Blue", 4: "Class A Blue-White", 5: "Class F White", 6: "Class G Yellow", 7: "Class K Orange", 8: "Class M Red", 9: "Class M Red", 10: "Class M Red", 11: "Class T Brown", 12: "Class D White", } return spectralclass.get(argument, "Sleepy Dwarf") def luminosity(argument): # Updated to the VBAM Galaxies Ruleset. if (argument<12): s = (random.randint(1,6)+random.randint(1,6)); if (argument>11): s = 13; luminosity = { 2: "Class I Supergiant", 3: "Class II Bright Giant", 4: "Class III Giant", 5: "Class IV Subgiant", 6: "Class V Main Sequence", 7: "Class V Main Sequence", 8: "Class V Main Sequence", 9: "Class V Main Sequence", 10: "Class V Main Sequence", 11: "Class VI Subdwarf", 12: "Class VI Subdwarf", 13: "Class VII White Dwarf", } return luminosity.get(s, "white hole") def stellarsystem(): r=(random.randint(1,6)+random.randint(1,6)-7) r = r+1 # This (r=r+1) is because the rules describe this roll # to be how many companion stars there might be. # but I need to know how many stars there are. if (r<1): r=1 if (r<1): stellartype = "black hole" if (r==1): stellartype = "single star" if (r==2): stellartype = "binary star" if (r==3): stellartype = "trinary star" if (r==4): stellartype = "quaternary star" if (r==5): stellartype = "quinternary star" if (r>5): stellartype = "sextenary star" return stellartype def numofstars(argument): numberofstars = { "black hole": 0, "single star": 1, "binary star": 2, "trinary star": 3, "quaternary star": 4, "quinternary star": 5, "sextenary star": 6, } return numberofstars.get(argument, 0) def systemimportancelevel(argument): # Brings in the 2d6 Roll from Spectral and then we apply the modifier. # Importantance Modifier by Spectral class if (argument==2): s = -6 #Class O if (argument==3): s = -4 #Class B if (argument==4): s = -2 # Class A if (argument==5): s = 1 #Class F if (argument==6): s = 2 #Class G Yellow if (argument==7): s = 0 #Class K Orange if (argument>7 and argument<11): s = -1 #class M Red if (argument==11): s = -5 #Class T Brown if (argument==12): s = -3 #class D White Dwarf s = (s + (random.randint(1,6)+random.randint(1,6))); if s < 2: s=2 if s > 12: s=12 return s def systemimportance(argument): # Updated to the VBAM Galaxies Ruleset. systemimportance = { 2: "Unimportant", 3: "Unimportant", 4: "Unimportant", 5: "Unimportant", 6: "Minor", 7: "Minor", 8: "Minor", 9: "Minor", 10: "Major", 11: "Major", 12: "Major", } return systemimportance.get(argument, "BespinCity") def starinnerplanets(argument): # Brings in the 2d6 Roll from Spectral and then we apply the modifier. # Importantance Modifier by Spectral class if (argument<4): s = 0 if (argument>3 and argument<7): s = 1 if (argument>6 and argument<10): s = 2 if (argument>9 and argument<12): s = 3 if (argument>11): s = 4 return s def starmiddleplanets(argument): # Brings in the 2d6 Roll from Spectral and then we apply the modifier. # Importantance Modifier by Spectral class if (argument<3): s = 0 if (argument>2 and argument<6): s = 1 if (argument>5 and argument<9): s = 2 if (argument>8): s = 3 return s def starouterplanets(argument): # Brings in the 2d6 Roll from Spectral and then we apply the modifier. # Importantance Modifier by Spectral class if (argument<5): s = 1 if (argument>4 and argument<8): s = 2 if (argument>7): s = 3 return s class planet(): def __init__(self,name,starname,zone): # OLD: rawweight = [0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,3,4,5,6] # OLD: bioweight = [0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4] innerzone = ["Asteroid Belt", "Gas Giant", "Hothouse", "Hothouse", "Dead", "Dead", "Superterrestrial", "Garden"] middlezone = ["Asteroid Belt", "Gas Giant", "Gas Giant", "Gas Giant", "Dead", "Dead", "Dead", "Barren", "Barren"] outerzone = ["Asteroid Belt", "Gas Giant", "Gas Giant", "Gas Giant", "Gas Giant", "Gas Giant", "Gas Giant", "Dead", "Dead", "Dead"] # TODO: Add Moons self.planetName = name self.starName = starname planettype = "" if (zone=="inner"): planettype = (random.choice(innerzone)) if (zone=="middle"): planettype = (random.choice(middlezone)) if (zone=="outer"): planettype = (random.choice(outerzone)) self.zone = zone self.planettype = planettype if (planettype == "Asteroid Belt"): self.planetSize = 2 self.planetBio = 0 self.planetRaw = 1 if (planettype == "Gas Giant"): self.planetSize = 4 self.planetBio = 0 self.planetRaw = 1 if (planettype == "Hothouse"): self.planetSize = 2 self.planetBio = 0 self.planetRaw = 2 if (planettype == "Superterrestrial"): self.planetSize = 6 self.planetBio = 1 self.planetRaw = 2 if (planettype == "Dead"): self.planetSize = 4 self.planetBio = 0 self.planetRaw = 1 if (planettype == "Barren"): self.planetSize = 6 self.planetBio = 1 self.planetRaw = 2 if (planettype == "Garden"): self.planetSize = 8 self.planetBio = 3 self.planetRaw = 4 # OLD: self.planetSize = (random.randint(1,4)) # OLD: self.planetBio = (random.choice(bioweight)) # OLD: self.planetRaw = (random.choice(rawweight)) def detailedPlanet(self): return self.zone + ": " + self.planetName + "(" + self.planettype + ") size: " + str(self.planetSize) + ", BIO: " + str(self.planetBio) + ", RAW: " + str(self.planetRaw) class star(): def __init__(self,name,systemname): self.starName = name self.starSystemName = systemname # # Star generation now follows the VBAM Galaxies ruleset on Google Docs. # # Star Spectral Class # Roll 2d6 for Spectral class. r=(random.randint(1,6)+random.randint(1,6)); # assign starspectral values self.starSpectral = spectralclass(r); self.starLuminosity = luminosity(r); self.systemimportancelevel = systemimportancelevel(r); self.systemimportance = systemimportance(self.systemimportancelevel) self.numofinnerplanets = starinnerplanets(self.systemimportancelevel); self.numofmiddleplanets =starmiddleplanets(self.systemimportancelevel); self.numofouterplanets = starouterplanets(self.systemimportancelevel); self.planets = []; def populateStar(self): x = self.numofinnerplanets for i in range(x): self.planets.append(planet("planet",self.starName,"inner")) x = self.numofmiddleplanets for i in range(x): self.planets.append(planet("planet",self.starName,"middle")) x = self.numofouterplanets for i in range(x): self.planets.append(planet("planet",self.starName,"outer")) def add_planet(self,planetname): self.planets.append(planet("planet",self.starName,zone)) def detailedStar(self): returntxt = self.starSystemName + " " + self.starName + ", a " + self.starSpectral + " " +self.starLuminosity returntxt = returntxt + " (" + self.systemimportance + ")" if (self.numofinnerplanets+self.numofmiddleplanets+self.numofouterplanets > 1): returntxt = returntxt + " with " + str(self.numofinnerplanets+self.numofmiddleplanets+self.numofouterplanets) + " planets." if (self.numofinnerplanets+self.numofmiddleplanets+self.numofouterplanets==1): returntxt = returntxt + " with a planet." if (self.numofinnerplanets+self.numofmiddleplanets+self.numofouterplanets<1): returntxt = returntxt + ", it is planetless." return returntxt class starSystem(): def __init__(self,name): self.starSystemName = name self.stellartype = stellarsystem() self.numofstars = numofstars(self.stellartype) self.coord_x = random.randint(1,500); self.coord_y = random.randint(1,500); self.coord_z = random.randint(1,20); self.stars = []; possiblejumps = [2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,5,5,6,6,7] jumppoints = (random.choice(possiblejumps)) jumppoints = (jumppoints-self.numofstars) if (jumppoints<1): jumppoints=1 if (jumppoints>6): jumppoints=6 self.numofJumps = jumppoints def add_star(self,starname): self.stars.append(star(starname,self.starSystemName)) def populateSystem(self): x = self.numofstars for i in range(x): if (i==6): self.stars.append(star("eta",self.starSystemName)) if (i==5): self.stars.append(star("zeta",self.starSystemName)) if (i==4): self.stars.append(star("epsilon",self.starSystemName)) if (i==3): self.stars.append(star("delta",self.starSystemName)) if (i==2): self.stars.append(star("gamma",self.starSystemName)) if (i==1): self.stars.append(star("beta",self.starSystemName)) if (i==0): self.stars.append(star("prime",self.starSystemName)) self.stars[(i)].populateStar() def detailedStarSystem(self): x = self.numofstars systemDetails=self.starSystemName + " is a " + self.stellartype + " system " systemDetails=systemDetails + "located at (" + str(self.coord_x) + "," + str(self.coord_y) + ","+ str(self.coord_z) +") " systemDetails=systemDetails + "with " + str(self.numofJumps) + " jumppoints.\n" while (x > 0): systemDetails = systemDetails + self.stars[x-1].detailedStar() + "\n" y=self.stars[x-1].numofinnerplanets+self.stars[x-1].numofmiddleplanets+self.stars[x-1].numofouterplanets while (y > 0): systemDetails = systemDetails + " " + self.stars[x-1].planets[y-1].detailedPlanet() + "\n" y=y-1 x=x-1 return systemDetails def buildStarCluster(): n = int(input('How many star systems?" ')) systempicks = ['Aldbaran','Andromeda','Capella','Centauri','Cerberus','Draconis','Gallus','Leo','Malus','Nihal','Orion','Rana'] for i in range(n): demostarsystem = starSystem(random.choice(systempicks)); starSystem.populateSystem(demostarsystem); print(demostarsystem.detailedStarSystem()); def main(): buildStarCluster(); if __name__ == "__main__": main()
ddc96de9135815055997e7833bf7ac5edc7aa6c3
SamBaker95/elephant_vending_machine_backend
/elephant_vending_machine/static/experiment/example_experiment.py
3,811
3.875
4
import random import time def run_experiment(experiment_logger, vending_machine): """This is an example of an experiment file used to create custom experiments. In this experiment, a fixation cross is presented on the center display and the other two displays randomly display either a white, or a black stimuli. The correct response is to select the white stimuli. The LEDs flash green if the correct choice was made. Parameters: experiment_logger: Instance of experiment logger for writing logs to csv files vending_machine: Instance of vending_machine for interacting with hardware devices """ NUM_TRIALS = 20 INTERTRIAL_INTERVAL = 5 # seconds BLANK_SCREEN = 'all_black_screen.png' FIXATION_STIMULI = 'fixation_stimuli.png' WHITE_STIMULI = 'white_stimuli.png' BLACK_STIMULI = 'black_stimuli.png' # Repeat trial for NUM_TRIALS iterations for trial_index in range(NUM_TRIALS): trial_num = trial_index + 1 experiment_logger.info("Trial %s started", trial_num) vending_machine.left_group.display_on_screen(BLANK_SCREEN) vending_machine.middle_group.display_on_screen(FIXATION_STIMULI) vending_machine.right_group.display_on_screen(BLANK_SCREEN) experiment_logger.info("Presented fixation cross") correct_response = False while not correct_response: # Wait for choice on left, middle, or right screens. Timeout if no selection after 5 minutes (300000 milliseconds) selection = vending_machine.wait_for_input([vending_machine.left_group, vending_machine.middle_group, vending_machine.right_group], 30000) if selection == 'middle': experiment_logger.info("Trial %s picked middle when selecting fixation cross", trial_num) # Flash middle screen LEDs green for 3 seconds (3000 milliseconds) vending_machine.middle_group.led_color_with_time(0, 255, 0, 3000) correct_response = True elif selection == 'left': experiment_logger.info("Trial %s picked left when selecting fixation cross", trial_num) elif selection == 'right': experiment_logger.info("Trial %s picked right when selecting fixation cross", trial_num) else: experiment_logger.info("Trial %s timed out when waiting to select fixation cross", trial_num) # Randomly decide to display white stimuli on left or right display white_on_left = random.choice([True, False]) if white_on_left: vending_machine.left_group.display_on_screen(WHITE_STIMULI) vending_machine.middle_group.display_on_screen(FIXATION_STIMULI) vending_machine.right_group.display_on_screen(BLACK_STIMULI) experiment_logger.info("Trial %s correct stimuli displayed on left", trial_num) else: vending_machine.left_group.display_on_screen(BLACK_STIMULI) vending_machine.middle_group.display_on_screen(FIXATION_STIMULI) vending_machine.right_group.display_on_screen(WHITE_STIMULI) experiment_logger.info("Trial %s correct stimuli displayed on right", trial_num) selection = vending_machine.wait_for_input([vending_machine.left_group, vending_machine.right_group], 300000) if selection == 'timeout': experiment_logger.info("Trial %s no selection made.", trial_num) elif selection == 'left': experiment_logger.info("Trial %s picked left", trial_num) else: experiment_logger.info("Trial %s picked right", trial_num) experiment_logger.info("Trial %s finished", trial_num) experiment_logger.info("Start of intertrial interval") # Wait for intertrial interval time.sleep(INTERTRIAL_INTERVAL) experiment_logger.info("End of intertrial interval") experiment_logger.info("Experiment finished")
19abf4589b03c1f8dc593bb6b2a446497fe31d72
danielnorberg/aoc2021
/23/day23_part1.py
897
3.5
4
from collections import deque def play(start_cups, n): cups = deque(int(c) for c in start_cups) for i in range(n): current = cups[0] cups.rotate(-1) removed = (cups.popleft(), cups.popleft(), cups.popleft()) cups.rotate(1) destination_label = current - 1 while destination_label in removed: destination_label -= 1 if destination_label not in cups: destination_label = max(cups) destination = cups.index(destination_label) cups.rotate(-(destination + 1)) cups.extendleft(reversed(removed)) cups.rotate(destination) cups.rotate(-cups.index(1)) cups.popleft() result = "".join(map(str, cups)) return result def main(): print(play('389125467', 10)) print(play('389125467', 100)) print(play('186524973', 100)) if __name__ == '__main__': main()
c482c05b0e8147e6c3edd7c29cbc6a26e0bd8589
randyhelzerman/ng
/python/p.py
2,371
3.5625
4
#!/usr/bin/python import argparse def main(): # find the file to read args = parseArguments() print args returner = parseFile(args.input) print returner if args.start and args.string: stringIterator = iterateString(args.string) success = execute(returner, args.start, stringIterator) if success: print "Success" else: print "Failure" def parseFile(fileName): with open(fileName) as fileStream: return parseStream(fileStream) def parseStream(stream): # initialize parse results with distincguisted end state returner = { 'END' : [] } for line in stream: parseLine(line, returner) return returner def parseLine( line, returner): tokens = line.strip().split() if len(tokens) < 3: return # If a successor state is not specified, # it means its going to the end state if len(tokens) == 3: tokens.append('END') # extract salient elements of the line stateName = tokens[0] charName = tokens[2][1:-1] successorStateName = tokens[3] if stateName in returner: returner[stateName].append( (charName, successorStateName)) else: returner[stateName] = [ (charName, successorStateName)] def parseArguments(): parser = argparse.ArgumentParser() parser.add_argument( "--input", help="input file", required=True) parser.add_argument( "--start", help="start symbol--start the parsing from here") parser.add_argument( "--string", help="string to parse") args = parser.parse_args() return args def execute( nfa, startState, stringIterator): states= set(startState) for character in stringIterator: states = executeStep(nfa, states, character) if "END" in states: return True if len(states) == 0: return False return False def executeStep(nfa, states, character): returner = set() for state in states: for arc in nfa[state]: if arc[0] == character: returner.add(arc[1]) return returner def iterateString(string): for character in string: yield character if __name__ == "__main__": main()