blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
dd7c7d610693962c38b03cad154d0bcedd243ad8
smile0304/py_asyncio
/chapter11/thread_sync.py
552
3.671875
4
import threading from threading import Lock,RLock total = 0 lock = RLock() def add(): global lock global total for i in range(1000000): lock.acquire() lock.acquire() total += 1 lock.release() lock.release() def desc(): global lock global total for i in range(1000000): lock.acquire() total -= 1 lock.release() thread1 =threading.Thread(target=add) thread2 =threading.Thread(target=desc) thread1.start() thread2.start() thread1.join() thread2.join() print(total)
7d22306762bb54a09f2d764a83bc8ed60ea8c706
smile0304/py_asyncio
/chapter05/biset_test.py
314
3.8125
4
import bisect #用来处理已排序的序列,用来维持已排序序列(升序) #二分查找 inter_list = [] bisect.insort(inter_list,3) bisect.insort(inter_list,2) bisect.insort(inter_list,5) bisect.insort(inter_list,1) bisect.insort(inter_list,6) print(bisect.bisect_left(inter_list,3)) print(inter_list)
ae591c5ccda56d20dd75a06bbbec5ba51556efe0
Hassiad/100-days-of-Code-Python
/20_21-Snake_Game/main.py
1,236
3.796875
4
# Day 20 and 21 Snake Game from turtle import Turtle, Screen from snake import Snake from food import Food from scoreboard import Scoreboard import time """Screen setup""" screen = Screen() screen.setup(width=600,height=600) screen.bgcolor("black") screen.title("Timmy Snake Game") screen.tracer(0) """Initial 3 segments of snake named Timmy""" timmy = Snake() food = Food() scoreboard = Scoreboard() """Snake Movement""" screen.listen() screen.onkey(timmy.up, "Up") screen.onkey(timmy.down, "Down") screen.onkey(timmy.left, "Left") screen.onkey(timmy.right, "Right") game_is_on = True while game_is_on: screen.update() time.sleep(0.1) timmy.move() """Detect collision with food""" if timmy.head.distance(food) < 15: food.refresh() scoreboard.increase_score() timmy.extend() """Detect collision with wall""" if timmy.head.xcor()>290 or timmy.head.xcor()<-290 or timmy.head.ycor()>290 or timmy.head.ycor()<-290: scoreboard.game_over() game_is_on = False """Detect collision with tail""" for segment in timmy.segments[1:]: if timmy.head.distance(segment)<10: scoreboard.game_over() game_is_on = False screen.exitonclick()
acf5a86f8be7589c70c6156e8935379ba7295a1d
akashsury/Operations
/Operations.py
1,683
3.8125
4
class Operations: def __init__(self): pass def aboveBelow(self, values, comparison): dict = {"above": 0, "below": 0} # created as local variable, each call it has to have zero if not isinstance(comparison, int) or not isinstance(values, list): return False for value in values: if not isinstance(value, int): return False elif value > comparison: dict["above"] += 1 elif value < comparison: dict["below"] += 1 return dict def stringRotation(self, input_string, rotation_value): if not isinstance(input_string, str) or not isinstance(rotation_value, int) or rotation_value < 0: return False if input_string: # For handling Zero division str_len = len(input_string) rotate_by = rotation_value % str_len return input_string[str_len - rotate_by:] + input_string[:str_len - rotate_by] return input_string operation = Operations() print(operation.aboveBelow([1, 2, 3, 4, 5, 6], 3)) print(operation.aboveBelow([1, 2, 3, 4, 5, 6], -1)) print(operation.aboveBelow([1, 2, 3, 4, 5, 6], 100)) print(operation.aboveBelow([], 3)) print(operation.aboveBelow([3, 3, 3], 3)) print(operation.stringRotation("MyString", 2)) print(operation.stringRotation("MyString", 2001)) print(operation.stringRotation("MyString", 0)) print(operation.stringRotation("", 10)) # For invalid inputs printing false print(operation.aboveBelow("", 3)) print(operation.stringRotation(3, 2)) print(operation.stringRotation("Mystring", -1))
f0206ac8aa63ea9b17d861d3115932b014abcbfc
sensecollective/bioinformatics-coursera
/find_sequence.py
524
3.578125
4
#!/usr/bin/env python import sys import operator #first argument is a single-line fasta input seq_f = sys.argv[1] f = open(seq_f) #f.readline() #toss input line seq = f.readline() #grab fasta seq = seq.strip() kmer = f.readline().strip() #grab kmer f.close() #second argument is the k-mer to find #kmer = sys.argv[2] k = len(kmer) count = 0 print seq print kmer #generate a list of all k-mers for mer in [seq[i:i+k] for i in xrange(len(seq)-(k-1))]: print mer if mer == kmer: count += 1 print count
97001f35773373489d615f21fd25d2cba18a20ef
Nisarga-AC/python-for-mbas
/Part 1/strings.py
720
4.0625
4
# Strings are text surrounded by quotes # Both single (' ') and double (" ") can be used kanye_quote = ('My greatest pain in life is that I will never ' 'be able to see myself perform live.') print(kanye_quote) # Switch to single quotes if your string uses double-quotes hamilton_quote = 'Well, the word got around, they said, "This kid is insane, man"' print(hamilton_quote) # A few string functions print(kanye_quote.upper()) print(kanye_quote.lower()) print("ok fine".replace("fine", "great").upper()) # F-Strings let you write Python code directly inside of a string # inside of curly brackets ({ }) print(f"1 + 1 equals {1 + 1}") name = "mattan griffel" print(f"{name.title()}, the total will be ${200 + 121.8 :,.2f}")
1c1c65e73e9072be54e5428f4a9c4f95745658e9
yyassif/My_Util_Scripts
/multi_threading.py
1,450
3.578125
4
import threading import time class MyThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting", self.name, "\n") thread_lock.acquire() print_time(self.name, 1, self.counter) thread_lock.release() print("Exiting", self.name, "\n") class MyThread2(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting", self.name, "\n") thread_lock.acquire() thread_lock.release() print_time(self.name, 1, self.counter) print("Exiting", self.name, "\n") def print_time(threadName, delay, counter): while counter: time.sleep(delay) print(f"{threadName}: {time.ctime(time.time())} {counter}") counter -= 1 # Lock the thread thread_lock = threading.Lock() # Create new Threads thread1 = MyThread(1, "Payment", 5) thread2 = MyThread2(2, "Sending Email", 10) thread3 = MyThread2(3, "Loading Page", 3) # Start new Threads thread1.start() thread2.start() thread3.start() # This helps you execute loading the page while the email is being sent # which will save much more time # And the user won't be upset thread1.join() thread2.join() thread3.join() print("Exiting Main Thread")
ba84d228a663b9c9dce7dc8fc2916a55fca1305b
PrajaktaJadhav2/Problems-on-DS-and-Algos
/The_Celebrity_Problem.py
1,421
4.03125
4
# Problem Statement # A celebrity is a person who is known to all # but does not know anyone at a party. # If you go to a party of N people, find if there is a celebrity in the party or not. import numpy as np def celebrity(): n = int(input("Enter the number of people")) matrix = [] #Get the number of people for i in range(n): a = [] for j in range(n): k = int(input()) val = check(k) a.append(val) matrix.append(a) for i in range(n): for j in range(n): print(matrix[i][j],end=" ") print() ans = -1 for i in range(n): count = 0 for j in matrix[i]: if j == 0 : count = count + 1 else: break if count==n and ans == -1: ans = i elif count==n: return ans return ans #Check if the valid input is been taken def check(k): if(k==0 or k==1): return k else: print("Invalid param") k = int(input()) check(k) ans = celebrity() print(ans) # Output # Enter the number of people 3 # 0 # 1 # 0 # 0 # 0 # 0 # 1 # 0 # 0 # 0 1 0 # 0 0 0 # 1 0 0 # 1 # Explanation : Person 1 doesn't know anyone. Therefore, 1 is the celebrity # Enter the number of people2 # 1 # 0 # 0 # 1 # 1 0 # 0 1 # -1 # Nobody is celebrity
da34092f0d87be4f33072a3e2df047652fb29cf3
sudj/24-Exam3-201920
/src/problem2.py
2,658
4.125
4
""" Exam 3, problem 2. Authors: Vibha Alangar, Aaron Wilkin, David Mutchler, Dave Fisher, Matt Boutell, Amanda Stouder, their colleagues and Daniel Su. January 2019. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. def main(): """ Calls the TEST functions in this module. """ run_test_shape() def run_test_shape(): """ Tests the shape function. """ print() print('--------------------------------------------------') print('Testing the SHAPE function:') print('There is no automatic testing for this one; just compare it' 'to the expected output given in the comments:') print('--------------------------------------------------') print() print('Test 1 of shape: n=5') shape(5) print() print('Test 2 of shape: n=3') shape(3) print() print('Test 3 of shape: n=9') shape(9) def shape(n): #################################################################### # IMPORTANT: In your final solution for this problem, # you must NOT use string multiplication. #################################################################### """ Prints a shape with numbers on the left side of the shape, other numbers on the right side of the shape, and stars in the middle, per the pattern in the examples below. You do NOT need to deal with any test cases where n > 9. It looks like this example for n=5: 11111* 2222*1 333*12 44*123 5*1234 And this one for n=3: 111* 22*1 3*12 And this one for n=9: 111111111* 22222222*1 3333333*12 444444*123 55555*1234 6666*12345 777*123456 88*1234567 9*12345678 :type n: int """ # ------------------------------------------------------------------ # DONE: 2. Implement and test this function. # Some tests are already written for you (above). #################################################################### # IMPORTANT: In your final solution for this problem, # you must NOT use string multiplication. #################################################################### for k in range(n): for j in range(n - k): print(k + 1, end='') if k == 0: print('*') else: print('*', end='') for l in range(k): if l == (k - 1): print(l + 1) else: print(l + 1, end='') # ---------------------------------------------------------------------- # Calls main to start the ball rolling. # ---------------------------------------------------------------------- main()
b2e763e72dd93b471294f997d2c18ab041ad665c
Evanc123/interview_prep
/gainlo/3sum.py
1,274
4.375
4
''' Determine if any 3 integers in an array sum to 0. For example, for array [4, 3, -1, 2, -2, 10], the function should return true since 3 + (-1) + (-2) = 0. To make things simple, each number can be used at most once. ''' ''' 1. Naive Solution is to test every 3 numbers to test if it is zero 2. is it possible to cache sum every two numberse, then see if the rest make zero? Insight: we need enough "power" in the negative numbers to reduce the positive numbers. Count up the negative numbers summed to see the maximum negative number. Possibly create some sort of binary search tree, where all the sums are the roots? No that wouldn't work. ''' def sum_2(arr, target): dict = {} for i in range(len(arr)): complement = target - arr[i] if complement in dict: return True dict[arr[i]] = i return False def sum_3(arr): arr.sort() for i in range(len(arr)): if sum_2(arr[:i] + arr[i+1:], -arr[i]): return True return False test = [4, 3, -1, 2, -2, 10] assert sum_3(test) == True test = [4, -4, 0] assert sum_3(test) == True test = [4, -3, -1] assert sum_3(test) == True test = [0, 0, 1] assert sum_3(test) == False test = [0, 2, -1, -5, 20, 10, -2] assert sum_3(test) == True
c40c9fcd27f8cf8f9ecf46cf7c576507450fb6e3
Evanc123/interview_prep
/dynamic_programming/edit_distance.py
2,307
3.96875
4
# A Naive recursive Python program to fin minimum number # operations to convert str1 to str2 def editDistance(str1, str2, m , n): # If first string is empty, the only option is to # insert all characters of second string into first if m==0: return n # If second string is empty, the only option is to # remove all characters of first string if n==0: return m # If last characters of two strings are same, nothing # much to do. Ignore last characters and get count for # remaining strings. if str1[m-1]==str2[n-1]: return editDistance(str1,str2,m-1,n-1) # If last characters are not same, consider all three # operations on last character of first string, recursively # compute minimum cost for all three operations and take # minimum of three values. return 1 + min(editDistance(str1, str2, m, n-1), # Insert editDistance(str1, str2, m-1, n), # Remove editDistance(str1, str2, m-1, n-1) # Replace ) # A Dynamic Programming based Python program for edit # distance problem def editDistDP(str1, str2, m, n): # Create a table to store results of subproblems dp = [[0 for x in range(n+1)] for x in range(m+1)] # Fill d[][] in bottom up manner for i in range(m+1): for j in range(n+1): # If first string is empty, only option is to # isnert all characters of second string if i == 0: dp[i][j] = j # Min. operations = j # If second string is empty, only option is to # remove all characters of second string elif j == 0: dp[i][j] = i # Min. operations = i # If last characters are same, ignore last char # and recur for remaining string elif str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] # If last character are different, consider all # possibilities and find minimum else: dp[i][j] = 1 + min(dp[i][j-1], # Insert dp[i-1][j], # Remove dp[i-1][j-1]) # Replace return dp[m][n] # Driver program to test the above function str1 = "sunday" str2 = "saturday" print editDistance(str1, str2, len(str1), len(str2))
408aa37f423d41ae5b724fbae02a5a92228ddfb0
packetbuddha/SecretSanta
/secret_santa/secret_santa.py
4,923
3.53125
4
#!/usr/bin/env python """ Description: Plays traditional Secret Santa game, printing results to stdout, to files or send via email. Author: Carl Tewksbury Last Update: 2019-11-27 - Py3-ize; remove unneeded passing of couples var; email auth password now in file. """ # stdlib import random import yaml import copy from datetime import date # local import ssmail class SecretSanta(object): def __init__(self, santa_config=None, debug=False, write=False, email=False): self.santas_config = santa_config self.couples = self._load_config() self.debug = debug self.write = write self.email = email d = date.today() self.year = d.year def badmatch(self, santa, pick): """ Santa can't pick themselves or anyone in their immediate family Args: couples (list): list of tuples, each containing persons who should not be matched together Returns: True if is bad match, False otherwise """ res = False if santa == pick or self.couples[santa]['family'] == self.couples[pick]['family']: res = True return res def deadend(self, hat, santa, pick): """ Detect dead ends - a badmatch() is the only available pick """ res = False if (len(hat) <= 2) and (self.badmatch(santa, pick)): print("only {0} left: {1}".format(len(hat), hat)) res = True return res def pick_from_the_hat(self, secretsantas, hat, santa): """ Randomly select from the hat and check if its a good pick """ pick = random.choice(hat) print("santa picked {}".format(pick)) if self.deadend(hat, santa, pick): res = ("deadend") elif self.badmatch(santa, pick): res = ("badmatch") else: hat.remove(pick) print("looks good, man! I removed {} from the hat!".format(pick)) res = pick return res def play(self, secretsantas, hat): """ Wrapper for picking function to deal with the results; such as dead ends resulting in the need to start the game over again """ for santa, pick in secretsantas.items(): santaschoice = False while santaschoice == False: print('santa is {} ... '.format(santa), end='') mypick = self.pick_from_the_hat(secretsantas, hat, santa) if mypick == "deadend": print("crap, deadend!") return True elif mypick == "badmatch": print("crap, bad match!") continue elif mypick: print("adding match...", santa, "->", mypick) secretsantas[santa] = mypick santaschoice = True return False def _makefiles(self, secretsantas): for santa, child in secretsantas.items(): message = santa + ' is secret santa for: ' + child santaf = '/tmp/' + santa + '_secret_santa.txt' with open(santaf, 'w+') as f: f.write(message) def _sendmail(self, secretsantas): for santa, child in secretsantas.items(): to_address = self.couples[santa]['email'] print(to_address, santa, child) e = ssmail.Email(santa=santa, child=child, to_address=to_address, debug=self.debug) r = e.send() def _load_config(self): with open(self.santas_config, 'r') as f: return yaml.safe_load(f) def makefiles(self, secretsantas): for santa, pick in secretsantas.iteritems(): message = '{0} is secret santa for: {1} '.format(santa, pick) santaf = '/tmp/{0}_SecretSanta-{1}.txt'.format(santa, self.year) with open(santaf, 'w+') as f: f.write(message) def run(self): keepplaying = True while keepplaying: hat = [] secretsantas = {} # Each time we play again, reinitialize the elves data self.couples = self._load_config() if self.debug: print(self.couples) # Create list of santas in the hat using couples data secretsantas = copy.deepcopy(self.couples) for santa in secretsantas: hat.append(santa) keepplaying = self.play(secretsantas, hat) if self.debug: print('secret santas: {}'.format(secretsantas)) print('makefile:', self.write) print('sendmail:', self.email) if self.write: self._makefiles(secretsantas) if self.email: print('...sending emails!') self._sendmail(secretsantas) return secretsantas
0664bf4c09687ee98fb8f81d11c6691ddaa67642
CrazyCoder4Carrot/lintcode
/python/Reverse Linked List II.py
1,155
3.890625
4
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The head of linked list @param m: start position @param n: end position """ def reverseBetween(self, head, m, n): # write your code here if not head or m >= n: return head dummyhead = ListNode(0, head) start = head pre = dummyhead m -= 1 while m and start: m -= 1 pre = start start = start.next end = dummyhead while n and end: n -= 1 end = end.next next = end.next end.next = None newhead = self.reverse(start) pre.next = newhead start.next = next return dummyhead.next def reverse(self, head): if not head or not head.next: return head pre = None cur = head while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre
fa7f6f44b5a764f35e32120ecb1dba1595c16dd6
CrazyCoder4Carrot/lintcode
/python/Subsets.py
499
3.75
4
class Solution: """ @param S: The set of numbers. @return: A list of lists. See example. """ def subsets(self, S): # write your code here res = [] S.sort() self.search(S, [], 0, res) return res def search(self, nums, temp, index, res): if index == len(nums): res.append(temp) return self.search(nums, temp + [nums[index]], index + 1, res) self.search(nums, temp, index + 1, res)
152113e43cceee7807ab807267ca54fb2a1d1c19
CrazyCoder4Carrot/lintcode
/python/Search a 2D Matrix.py
352
3.765625
4
class Solution: """ @param matrix, a list of lists of integers @param target, an integer @return a boolean, indicate whether matrix contains target """ def searchMatrix(self, matrix, target): # write your code here for row in matrix: if target in row: return True return False
96df8f1ee63a40fde99d66d6218987cf119a12e6
CrazyCoder4Carrot/lintcode
/python/Swap Two Nodes in Linked List.py
1,319
3.953125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head, a ListNode # @oaram {int} v1 an integer # @param {int} v2 an integer # @return {ListNode} a new head of singly-linked list def swapNodes(self, head, v1, v2): # Write your code here if not head: return head dummyhead = ListNode("#") dummyhead.next = head ptr1 = dummyhead while ptr1.next and ptr1.next.val != v1: ptr1 = ptr1.next ptr2 = dummyhead while ptr2.next and ptr2.next.val != v2: ptr2 = ptr2.next if not ptr1.next or not ptr2.next: return head temp1 = ptr1.next temp2 = ptr2.next if temp2 == ptr1: ptr2.next = temp1 temp = temp1.next temp1.next = temp2 temp2.next = temp elif temp1 == ptr2: ptr1.next = temp2 temp = temp2.next temp2.next = temp1 temp1.next = temp else: ptr1.next = temp2 ptr2.next = temp1 temp = temp1.next temp1.next = temp2.next temp2.next = temp return dummyhead.next
5ebd4c91bd2fd1b34fbfdcff3198aef77ceb8612
CrazyCoder4Carrot/lintcode
/python/Insert Node in a Binary Search Tree.py
1,676
4.25
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ Revursive version """ class Solution: """ @param root: The root of the binary search tree. @param node: insert this node into the binary search tree. @return: The root of the new binary search tree. """ def insertNode(self, root, node): # write your code here if not root: root = node return root if root.val > node.val: if not root.left: root.left = node else: self.insertNode(root.left, node) return root else: if not root.right: root.right = node else: self.insertNode(root.right, node) return root """ Iteration version """ class Solution: """ @param root: The root of the binary search tree. @param node: insert this node into the binary search tree. @return: The root of the new binary search tree. """ def insertNode(self, root, node): # write your code here if not root: root = node return root cur = root while cur: if cur.val > node.val: if cur.left: cur = cur.left else: cur.left = node break else: if cur.right: cur = cur.right else: cur.right = node break return root """ Refined iteration version """
d14d74df34371a880c57f2580e2f27cc9a35aee6
CrazyCoder4Carrot/lintcode
/python/Insertion Sort List.py
1,696
3.921875
4
""" 932ms version insert node in the same list """ class Solution: """ @param head: The first node of linked list. @return: The head of linked list. """ def insertionSortList(self, head): # write your code here cur = head index = head tempmax = head.val while index.next: if tempmax < index.next.val: index = index.next tempmax = index.val continue cur = head if cur.val > index.next.val: temp = index.next index.next = index.next.next head = temp temp.next = cur continue while cur.next and cur != index and cur.next.val < index.next.val: cur = cur.next if cur: if cur == index: index = index.next continue else: temp = index.next index.next = index.next.next temp.next = cur.next cur.next = temp return head """ 645 ms convert list to array, sort the array then convert it to the list """ class Solution: """ @param head: The first node of linked list. @return: The head of linked list. """ def insertionSortList(self, head): # write your code here cur = head temp = [] while cur: temp.append(cur.val) cur = cur.next cur = head temp.sort() i = 0 while cur: cur.val = temp[i] i += 1 cur = cur.next return head """ """
1a5645ba8a8b640312045416a97fcabd7ff14e6e
CrazyCoder4Carrot/lintcode
/python/Rotate List.py
918
3.96875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head: the list # @param k: rotate to the right k places # @return: the list after rotation def rotateRight(self, head, k): # write your code here if not head or not head.next: return head cur = head count = 0 while cur: count += 1 cur = cur.next k = k % count if not k: return head cur = head while k and cur.next: cur = cur.next k-=1 if k: return head pre = head while pre and cur.next: pre = pre.next cur = cur.next temp = head head = pre.next pre.next = None cur.next = temp return head
0046fd9fa359ebfaa81b7fb40ecf2c5f6d278273
sfagnon/stephane_fagnon_test
/QuestionA/QaMethods.py
1,120
4.21875
4
#!/usr/bin/python # -*- coding: utf-8 -*- #Verify if the two positions provided form a line def isLineValid(line_X1,line_X2): answer = True if(line_X1 == line_X2): answer = False print("Points coordinates must be different from each other to form a line") return answer #Verify if the two positions provided form respectively the lower bound and the upper bound of #the line def verifyLineCoordinates(line): line_X1 = line[0] line_X2 = line[1] #Swap the line's bounds if(line_X1 > line_X2): temporary_point = line_X1 line_X1 = line_X2 line_X2 = temporary_point print("Line Coordinates\' bounds have been swapped from X1 = "+str(line_X2)+" and X2 = "+str(line_X1)+ "\n Line is now: ("+str(line_X1)+","+str(line_X2)+")") line = [line_X1,line_X2] return line #Check if a position bound belongs to a line interval (represented by its bounds) def isValueInInterval(value,lower_bound,upper_bound): answer = False if((lower_bound<=value) and (upper_bound>=value)): answer = True return answer
7a50c599822eba23ea3de2e98fe95a7fdc7c8152
PanQnshT/Projekt_X
/ship.py
1,149
3.53125
4
import pygame from pygame.math import Vector2 class Ship(object): def __init__(self, game): self.game = game size = self.game.screen.get_size() self.speed = 1.5 self.opor = 0.85 self.gravity = 0.5 self.pos = Vector2(size[0]/2,(size[1]/2)-(size[1]/4)) self.vel = Vector2(0,0) self.acc = Vector2(0,0) def add_force(self, force): self.acc += force def tick(self): # Input pressed = pygame.key.get_pressed() if pressed[pygame.K_UP]: self.add_force(Vector2(0,-self.speed)) if pressed[pygame.K_DOWN]: self.add_force(Vector2(0,self.speed)) if pressed[pygame.K_RIGHT]: self.add_force(Vector2(self.speed,0)) if pressed[pygame.K_LEFT]: self.add_force(Vector2(-self.speed,0)) # Physics self.vel *= self.opor self.vel -= Vector2(0, -self.gravity) self.vel += self.acc self.pos += self.vel self.acc *= 0 def draw(self): pygame.draw.rect(self.game.screen, (50, 100, 200), pygame.Rect(self.pos.x, self.pos.y, 25, 25))
f65179cd3fa2f47d95a538cded047baaf18c4d1c
ares5221/python-Learning
/day04/MaxtRotation.py
546
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __mtime__ = '2018/6/7' """ array=[[col for col in range(4)] for row in range(4)] #初始化一个4*4数组 for row in array: #旋转前先看看数组长啥样 print(row) print('-----开始旋转矩阵----') for i, row in enumerate(array): for index in range(i, len(row)): tmp = array[index][i] # get each rows' data by column's index array[index][i] = array[i][index] # array[i][index] = tmp for r in array: print (r) print('--one big loop --')
e5a2135657bb8bf74063da10c85701b820cf386e
mc-cabe/CompareLists
/compareLists.py
192
3.59375
4
arr1 = [] arr1 = raw_input("please enter list1:") arr2 = [] arr2 = raw_input("please enter list2:") if arr1 == arr2: print "arrays are the same" else: print "arrays are not the same"
f15c286da0a0de84375e3f71b88b3a2711e74180
umemotsu/deimscripts
/generateVoteData.py
1,724
3.578125
4
#coding:utf-8 # generateVoteData import csv, sys # read participan data def readParticipants(filename): partList = {} with open(filename,'rb') as csvfile: reader = csv.reader(csvfile,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL) for row in reader: person = {} person["partID"] = row[0] person["type"] = row[1] person["PosVoteID"] = row[2] partList[row[2]] = person csvfile.close() return partList # reader vote data generated by posvote def readPosVoteData(filename): voteList = {} with open(filename,'rb') as csvfile: reader = csv.reader(csvfile,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL) lineno = 0 for row in reader: lineno+=1 vote = {} if len(row)<2: sys.stderr.write("ERROR: line "+ str(lineno) + " has no vote information"+"\n".decode('utf-8')) continue else: vote["posVoteID"]=row[0] vote["data"]=row[1:len(row)] voteList[row[0]]=vote csvfile.close() return voteList # generate vote data def generateVoteData(partList, voteList): voteData = {} for vote in voteList: if vote in partList: participant = partList[vote] for d in voteList[vote]["data"]: print participant["partID"]+","+participant["type"]+","+d else: sys.stderr.write("ERROR: "+vote+" does not exist") continue # main procedure if __name__ == '__main__': partList = readParticipants(sys.argv[1]) voteList = readPosVoteData(sys.argv[2]) generateVoteData(partList, voteList)
06176687b50a2f17535536bf922dc6254b5c348d
artmukr/Homework_4
/Homework_4.2.py
167
3.515625
4
link = input('Enter your link :') link = link.replace('https://', "") link=link.replace('www.', '') value_of_start = link.rfind('/') print(link[:value_of_start])
70d3fb39df6fd9c1e6f48569d0057d9c11c32dec
apotato369550/breadth-first-search-python
/main3.py
4,142
3.796875
4
# i think i get this # x and y # test it with another maze configuration def create_maze(): return [ "O..#.", ".#.#.", "....#", "#...#", "X.###" ] def create_maze_2(): return [ "...O##X", ".###...", ".####..", "...#...", "..###..", ".#.....", "...####" ] def create_adjacency_list(maze): total_nodes = 0 for row in maze: total_nodes += len(row) adjacency_list = [[] for i in range(total_nodes)] for row_index, row in enumerate(maze): for column_index, column in enumerate(row): # edit this to not include obstacles if column == "#": continue node = column_index + (row_index * len(maze[0])) if row_index > 0: # add top if maze[row_index - 1][column_index] != "#": adjacency_list[node].append(column_index + ((row_index - 1) * len(maze[0]))) if row_index < len(maze) - 1: # add bottom if maze[row_index + 1][column_index] != "#": adjacency_list[node].append(column_index + ((row_index + 1) * len(maze[0]))) if column_index > 0: # add to the left if maze[row_index][column_index - 1] != "#": adjacency_list[node].append((column_index - 1) + (row_index* len(maze[0]))) if column_index < len(maze) - 1: # add to the right if maze[row_index][column_index + 1] != "#": adjacency_list[node].append((column_index + 1) + (row_index* len(maze[0]))) return total_nodes, adjacency_list # print "" def breadth_first_search(start, destination, predecessor, distance, adjacency_list, maze, nodes): queue = [] visited = [False for x in range(nodes)] for i in range(nodes): distance[i] = [1000] predecessor[i] = -1 visited[start] = True distance[start] = 0 queue.append(start) while len(queue) != 0: u = queue[0] queue.pop(0) for i in range(len(adjacency_list[u])): if not visited[adjacency_list[u][i]]: # work on this visited[adjacency_list[u][i]] = True distance[adjacency_list[u][i]] = distance[u] + 1 predecessor[adjacency_list[u][i]] = u queue.append(adjacency_list[u][i]) if adjacency_list[u][i] == destination: return True return False def print_shortest_distance(maze): # start and destination coords should be like (x, y) nodes, adjacency_list = create_adjacency_list(maze) predecessor = [0 for i in range(nodes)] distance = [0 for i in range(nodes)] start = 0 destination = 0 for row_index, row in enumerate(maze): for column_index, column in enumerate(row): if column == "O": start = column_index + (row_index * len(maze[0])) if column == "X": destination = column_index + (row_index * len(maze[0])) print start print destination if not breadth_first_search(start, destination, predecessor, distance, adjacency_list, maze, nodes): print "Source and destination not connected" return path = [] crawl = destination path.append(crawl) while predecessor[crawl] != -1: path.append(predecessor[crawl]) crawl = predecessor[crawl] print "Shortest path length is : " + str(len(path)) + " " print "\nPath is: \n" # find a way to convert node number into coordinates (x, y) # use modulus?? maybe for i in range(len(path) - 1, -1, -1): coordinates = (path[i] % len(maze[0]), path[i] // len(maze[0])) print "Node Number: " + str(path[i]) + " Coordinates: " + str(coordinates) + " " # test with other configurations # then try with javascript maze = create_maze_2() print_shortest_distance(maze) # append up, down, left, right nodes # do i do it per node or per coordinate??? (x, y) or n??? # return an adjacency matrix
89df09062d2ccaefd9526ee559ee67bf9a837a39
AmrinderKaur1/turtle-crossing-start
/car_manager.py
2,061
3.640625
4
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 X = [-300, 300] Y_AXES_LIST = [[120, 220], [20, 120], [-120, -20], [-220, -120]] class CarManager: def __init__(self): self.all_cars = [] self.car_speed = STARTING_MOVE_DISTANCE def car_colors(self): clr = random.choice(COLORS) return clr def create_car(self): head = 0 random_chance = random.randint(1, 6) if random_chance == 1: random_y_axis = random.choice(Y_AXES_LIST) y = random.randint(random_y_axis[0], random_y_axis[1]) if y > 0: x_axis = X[1] head = 180 elif y < 0: x_axis = X[0] new_car = Turtle(shape="square") new_car.shapesize(stretch_len=2, stretch_wid=1) new_car.penup() new_car_color = self.car_colors() new_car.color(new_car_color) new_car.goto(x_axis, y) new_car.setheading(head) self.all_cars.append(new_car) new_t1 = Turtle(shape="circle") new_t1.shapesize(stretch_wid=0.5, stretch_len=0.5) new_t1.penup() new_t1.color("black") y_cor1 = y - 10 new_t1.goto(x_axis - 10, y_cor1) new_t1.setheading(head) self.all_cars.append(new_t1) new_t2 = Turtle(shape="circle") new_t2.shapesize(stretch_wid=0.5, stretch_len=0.5) new_t2.penup() new_t2.color("black") new_t2.goto(x_axis + 10, y_cor1) new_t2.setheading(head) self.all_cars.append(new_t2) def move_cars(self): for i in range(0, len(self.all_cars), 3): self.all_cars[i].forward(self.car_speed) self.all_cars[i+1].forward(self.car_speed) self.all_cars[i+2].forward(self.car_speed) def level_up(self): self.car_speed += MOVE_INCREMENT
e606335002d2e02b40b59538d2dc59aba70eed6f
ganjingcatherine/leetcode_python
/sort_by_leetcode/math/hard/780 reaching point.py
1,487
3.59375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ 一开始的思路是逆向推,目的坐标(tx, ty)肯定是由(tx-ty, ty)或(tx, ty-tx),但是坐标限定不为负数,因此比较tx、ty的大小可以唯一确定上一步的步骤 类似搜索的题,从终点往起点看,比较容易猜到正解。 这个题的关键点是,如果 ty > tx,那么必然是从 (tx, ty-tx)到达(tx, ty)这个状态的。 想明白上面,还需要知道一个优化的思路:取模不要一次一次相减 题目大意: 从点(x, y)出发经过一次移动可以到达(x + y, y)或者(x, x + y) 给定点(sx, sy)与(tx, ty),判断(sx, sy)是否可以经过若干次上述移动到达(tx, ty) 解题思路: 循环取余数 类似于辗转相除法(欧几里得算法) 当 tx > ty 时,找父母的操作就是 tx - ty, 直到 tx = tx % ty 为止。当 tx > ty 和 ty > sy 都满足时,我们可以使用 tx %= ty 来代替 while tx > ty: tx -= ty ,会更快。 当 tx > ty 且 ty = sy 时,我们知道 ty 不能再减了,所以只有 tx 会改变,并且只会通过 一步步地减去ty 来改变。所以,使用 (tx - sx) % ty == 0 会更高效。 ty > tx 的情形同理。可以一直这样做,直到 tx == ty, 此时不需要再做 move 了 """ while sx < tx and sy < ty: if tx > ty: tx %= ty else: ty %= tx if sx == tx: return (ty - sy) % sx == 0 if sy == ty: return (tx - sx) % sy == 0 return False
23167d9292e97e858d70c4836fe3f6cb4f09fc5f
getoverlove/Majiang
/eye/32-不放回摸球直到摸到a白b黑球的比例.py
1,309
3.609375
4
from fractions import Fraction from sympy import * f_dict = {} def f(m, n, a, b): """ m个白球,n个黑球,想要摸到a个白球,b个黑球 用递推式的方式计算准确结果,结果使用分数表示 """ assert a >= 0 and b >= 0 and m >= 0 and n >= 0 assert a <= m and b <= n param = (m, n, a, b) if param in f_dict: return f_dict[param] if a == 0 and b == 0: f_dict[param] = 0 return 0 if m == 0 or n == 0: f_dict[param] = max(a, b) return max(a, b) x = Fraction(m, m + n) y = Fraction(n, m + n) ans = 1 + x * f(m - 1, n, max(a - 1, 0), b) + y * f(m, n - 1, a, max(b - 1, 0)) f_dict[param] = ans return ans def test(): m, n, a, b = 7, 6, 3, 2 res = f(m, n, a, b) res = simplify(f"{res.numerator}/{res.denominator}") # 分类讨论最后一个球 rate1 = simplify(f"{m + 1}/ {m + n + 1}") rate2 = simplify(f"{n + 1}/ {m + n + 1}") last1 = a / rate1 last2 = b / rate2 print(f""" 期望摸球次数{res}次 如果最后一个球是白球,摸球次数{last1} 如果最后一个球是黑球,摸球次数{last2} """) x, y = symbols('x,y') system = [last1 * x + last2 * y - res, x + y - 1] ans = linsolve(system, (x, y)) print(ans) test()
c99ba21ebb47076b3fcefefc8d29e9ad6bcf50e3
getoverlove/Majiang
/eye/40-多目标不放回摸球每个目标与总目标的关系.py
2,083
3.796875
4
""" 当前局面到胡牌局面的差 D={d1,d2,d3......} 问题等价于:从一个袋子里面摸球,期望摸几次才能使pattern符合D中的任意一个。 例如2个白球3个黑球,摸到1个白球或者1个黑球时停止,此问题的答案会小于f(2,3,1,0)和f(2,3,0,1).显然此问题的答案会变成1. 麻将问题应该是一个多目标概率问题。 称此问题为:多目标摸球问题 """ from fractions import Fraction from copy import deepcopy noput_dict = {} def noput(m, n, a, b): """ m个白球,n个黑球,想要摸到a个白球,b个黑球 用递推式的方式计算准确结果,结果使用分数表示 """ assert a >= 0 and b >= 0 and m >= 0 and n >= 0 assert a <= m and b <= n param = (m, n, a, b) if param in noput_dict: return noput_dict[param] if a == 0 and b == 0: f_dict[param] = 0 return 0 if m == 0 or n == 0: f_dict[param] = max(a, b) return max(a, b) x = Fraction(m, m + n) y = Fraction(n, m + n) ans = 1 + x * noput(m - 1, n, max(a - 1, 0), b) + y * noput(m, n - 1, a, max(b - 1, 0)) noput_dict[param] = ans return ans f_dict = {} def f(m, n, target): # 多目标不放回摸球问题 assert m >= 0 and n >= 0 for a, b in target: assert m >= a >= 0 and n >= b >= 0 target = sorted(target) param = (m, n, str(target)) if param in f_dict: return f_dict[param] for a, b in target: if a == 0 and b == 0: f_dict[param] = 0 return 0 ans = 1 if m: ifA = deepcopy(target) for t in ifA: t[0] = max(t[0] - 1, 0) ans += Fraction(m, m + n) * f(m - 1, n, ifA) if n: ifB = deepcopy(target) for t in ifB: t[1] = max(t[1] - 1, 0) ans += Fraction(n, m + n) * f(m, n - 1, ifB) f_dict[param] = ans return ans target = [[1, 0], [1, 1]] m = 5 n = 3 for a, b in target: args = (m, n, a, b) print(args, noput(*args), f(m, n, [[a, b]])) print(f(m, n, target))
d83e883c6595e1e5eb646f96a9f12635b81839c0
shtakai/cd-python
/0502-am/assignment/scoresandgrades.py
789
4.03125
4
def scores_and_grades(): scores = [] for value in range(10): score = raw_input("Input Score {}:".format(value + 1)) scores.append(score) print "Scores and Grades" for score in scores: grade = "" score = int(score) if score >= 60 and score < 70: # print 'grade D',score grade = 'D' elif score >= 70 and score < 80: # print 'grade C',score grade = 'C' elif score >= 80 and score < 90: # print 'grade B',score grade = 'B' elif score >= 90 and score <= 100: # print 'grade A',score grade = 'A' print "Score: {}; Your grade is {}".format(score, grade) print "End of the program. Bye!" scores_and_grades()
753165690888d3364f9a6bb9de23a4e24b148f0f
shtakai/cd-python
/oop/assignment/linkedlist/linkedlist.py
2,725
4.0625
4
class Linkedlist(object): def __init__(self, value): self.value = value self.prev_node = None self.nxt_node = None print 'initialized node', self def insert_last(self, last_node): if last_node: last_node.nxt_node = self self.prev_node = last_node print 'this node',self,'added after last_node',self.prev_node else: print 'this node',self, 'added from empty' def delete(self): if self.nxt_node and self.prev_node: self.nxt_node.prev_node = self.prev_node self.prev_node.nxt_node = self.nxt_node print 'deleted node', self, 'between prev', self.prev_node, 'and next', self.nxt_node elif self.nxt_node: self.nxt_node.prev_node = None print 'deleted node', self, 'before nxt', self.nxt_node elif self.previous_node: self.prev_node.nxt_node = None print 'deleted node', self, 'nextto prev', self.prev_node else: pass self.prev_node = None self.nxt_node = None print 'finished deletion', self def insert_between(self, prev, nxt): print self, 'insert between', prev, 'and', nxt prev.nxt_node = self self.prev_node = prev nxt.prev_node = self self.nxt_node = nxt print 'inserted node', self, 'between prev', self.prev_node, 'and next', self.nxt_node def __show__(self): return self.value def __unicode__(self): return self.value def __repr__(self): return self.value def show(self): print self.prev_node, '- ', self, '-',self.nxt_node def show_prev(self): print 'SHOW PREV',self if self.prev_node: self.prev_node.show_prev() def show_nxt(self): print 'SHOW NXT',self if self.nxt_node: self.nxt_node.show_prev() elem_1 = Linkedlist('element_1') elem_2 = Linkedlist('element_2') elem_3 = Linkedlist('element_3') elem_4 = Linkedlist('element_4') elem_5 = Linkedlist('element_5') elem_6 = Linkedlist('element_6') # add node from empty elem_1.insert_last(None) elem_1.show() print "-" * 10 elem_2.insert_last(elem_1) elem_2.show() elem_2.prev_node.show() print "-" * 10 elem_3.insert_last(elem_2) elem_3.show() elem_3.prev_node.show() elem_3.prev_node.prev_node.show() elem_1.nxt_node.show() elem_1.nxt_node.nxt_node.show() elem_2.show() elem_2.prev_node.show() elem_2.nxt_node.show() print "-" * 10 elem_4.insert_between(elem_1,elem_2) elem_4.show() elem_4.nxt_node.show() elem_4.nxt_node.nxt_node.show() print "-" * 10 elem_2.delete() elem_2.show() elem_1.show() elem_3.show() elem_4.show()
0d7c64b809aaf2495587c01e21f76792733ed566
shtakai/cd-python
/0502-am/list.py
356
3.65625
4
ninjas = ['Rozen', 'KB', 'Oliver'] my_list = ['4' ,['list', 'in', 'a', 'list'], 987] empty_list = [] print ninjas print my_list print empty_list fruits = ['apple', 'banana', 'orange', 'strawberry'] vegetables = ['lettuce', 'cucumber', 'carrots'] fruits_and_vegetables = fruits + vegetables print fruits_and_vegetables salad = 3 * vegetables print salad
efbe44be5d1ab0fd9f75f373ed7c7bf1ea2cdda7
tt1998215/pythoncode1
/begin end.py
712
3.671875
4
# import functools # def log(func): # # @functools.wraps(func) # def wrapper(*args,**kw): # print("begin call %s():"%func.__name__) # res=func(*args,**kw) # print("the result of the program is {}".format(res)) # print("end call %s():"%func.__name__) # #resturn res # return wrapper # # @log # def f2(x,y): # return x+y # # def main(): # f2(4,6) # print("the name of the function is :"+f2.__name__) # # main() import sys def test(): args = sys.argv if len(args)==1: print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__=='__main__': test()
cdaee67ad742ae35588e82fd5682391750e4f583
tt1998215/pythoncode1
/Mydatetime.py
515
3.515625
4
from datetime import datetime,timezone,timedelta # print(datetime.now()) # utc_dt=datetime.utcnow().replace(tzinfo=timezone.utc) # print(utc_dt) # bj_dt=utc_dt.astimezone(timezone(timedelta(hours=8))) # print(bj_dt) import re def to_timestmap(dt_str,tz_str): input_dt=datetime.strptime(dt_str) time_zone_num=re.match(r'UTC([+|-][\d]{1,2}):00',tz_str).group(1) time_zone=timezone(timedelta(hours=int(time_zone_num))) input_dt_tz=input_dt.replace(tzinfo=time_zone) return input_dt_tz.timestamp() +
22ca752af618837890c074dfe20776c44f40fece
matteblack9/infoRetrieval
/searchEngine5.py
6,636
3.984375
4
""" This file contains an example search engine that will search the inverted index that we build as part of our assignments in units 3 and 5. """ import sys,os,re import math import sqlite3 import time # use simple dictionnary data structures in Python to maintain lists with hash keys docs = {} resultslist = {} term = {} # regular expression for: extract words, extract ID from path, check for hexa value chars = re.compile(r'\W+') pattid= re.compile(r'(\d{3})/(\d{3})/(\d{3})') # # Docs class: Used to store infromation about each unit document. In this is the Term object which stores each # unique instance of termid for a docid. # class Docs(): terms = {} # # Term class: used to store information for each unique termid # class Term(): docfreq = 0 termfreq = 0 idf = 0.0 tfidf = 0.0 # split on any chars def splitchars(line) : return chars.split(line) # this small routine is used to accumulate query idf values def elenQ(elen, a): return(float(math.pow(a.idf,2))+float(elen)) # this small routine is used to accumulate document tfidf values def elenD(elen, a): return(float(math.pow(a.tfidf,2))+float(elen)) """ ================================================================================================ >>> main This section is the 'main' or starting point of the indexer program. The python interpreter will find this 'main' routine and execute it first. ================================================================================================ """ if __name__ == '__main__': # # Create a sqlite database to hold the inverted index. The isolation_level statment turns # on autocommit which means that changes made in the database are committed automatically # con = sqlite3.connect("/Data/SourceCode/infoRetrieval/indexer_part1.db") con.isolation_level = None cur = con.cursor() # # # line = input('Enter the search terms, each separated by a space: ') # # Capture the start time of the search so that we can determine the total running # time required to process the search # t2 = time.localtime() print('Start Time: %.2d:%.2d:%.2d' % (t2.tm_hour, t2.tm_min, t2.tm_sec)) # # This routine splits the contents of the line into tokens l = splitchars(line) # # Get the total number of documents in the collection # q = "select count(*) from DocumentDictionary" cur.execute(q) row = cur.fetchone() documents = row[0] # Initialize maxterms variable. This will be used to determine the maximum number of search # terms that exists in any one document. # maxterms = float(0) # process the tokens (search terms) entered by the user for elmt in l: # This statement removes the newline character if found elmt = elmt.replace('\n','') # This statement converts all letters to lower case lowerElmt = elmt.lower().strip() # # Execute query to determine if the term exists in the dictionary # q = "select count(*) from termdictionary where term = '%s'" % (lowerElmt) cur.execute(q) row = cur.fetchone() # # If the term exists in the dictionary retrieve all documents for the term and store in a list # if row[0] > 0: q = "select distinct docid, tfidf, docfreq, termfreq, term from posting where term = '%s' order by docid" % (lowerElmt) cur.execute(q) for row in cur: i_term = row[4] i_docid = row[0] if not ( i_docid in docs.keys()): docs[i_docid] = Docs() docs[i_docid].terms = {} if not ( i_term in docs[i_docid].terms.keys()): docs[i_docid].terms[i_docid] = Term() docs[i_docid].terms[i_docid].docfreq = row[2] docs[i_docid].terms[i_docid].termfreq = row[3] docs[i_docid].terms[i_docid].idf = 0.0 docs[i_docid].terms[i_docid].tfidf = row[1] resultslist = docs if len(resultslist) == 0: print ('There are no documents containing any of your query terms.') # # Calculate tfidf values for both the query and each document # Using the tfidf (or weight) value, accumulate the vectors and calculate # the cosine similarity between the query and each document # # # Calculate the denominator which is the euclidean length of the query # multipled by the euclidean lenght of the document # # # This search engine will match on any number of terms and the cosine similarity of a # docment matches on 1 term that appears in a document in the collection tends to score highly # the float(no_terms/maxtersm) portion of the equation is designed to give a higher weight # to documents that match on more than 1 term in queries that have multiple terms. # The remainder of the equation calculates the cosine similarity # # # Sort the results found in order of decreasing cosine similarity. Becuase we cannot use a float # value as an index to a list, I multipled the cosine similarity value by 10,000 and converted # to an integer. For example if the cosine similarity was calculated to be .98970 multiplying # it by 10,000 would produce 9897.0 and converting to an integer would result in 9897 which can be # used as an index that we can then sort in reverse order. To display the cosine similarity # correctly in the results list we simply convert it back to a float value and divide by 10,000 # keylist = resultslist.keys() # sort in descending order keylist.sort(reverse=True) i = 0 # print out the top 20 most relevant documents (or as many as were found) for key in keylist: i+= 1 if i > 20: continue q = "select DocumentName from DocumentDictionary where docid = '%d'" % (key) cur.execute(q) row = cur.fetchone() print ("Document: %s Has cosine similarity of %f" % (row[0], float(key)/10000)) con.close() # # Print ending time to show the processing duration of the query. # t2 = time.localtime() print ('End Time: %.2d:%.2d:%.2d' % (t2.tm_hour, t2.tm_min, t2.tm_sec)) print ('Total candidate documents:', len(docs))
b24483771fe532d0641a9025558c07fab2559f75
kushaswani/Insight_DE_Challenge
/src/consumer_complaints.py
1,995
3.6875
4
import csv import sys # from read_csv import read_csv # importing read_and_transform_csv function which lets you apply custom functions to rows and get the transformed dataframe as dict of arrays from read_csv import read_and_transform_csv # importing the custom function which we need to apply to get intended results from function_to_apply import foo # importing Decimal and ROUND_HALF_UP to round [0.5,1] to 1 and [0,0.5) to 0 from decimal import Decimal, ROUND_HALF_UP # getting the input and output filepaths from command line arguments input_filepath = sys.argv[1] output_filepath = sys.argv[2] # print(input_filepath) # print(output_filepath) # getting the intended result through applying the custom function to every row result = read_and_transform_csv(filepath = input_filepath, foo = foo, result = {}) # writing the result to a csv file with open(output_filepath, 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',') # Used tuple of (product,year) as key for k,v in result: # k[0] represents products, k[1] represents year, v[0] represents total number of complaints received for that product and year # v[1] represents a dictionary with companies as keys and their number of instances as values # therefore len(v[1]) gives the total number of companies receiving at least one complaint for that product and year row = [k[0],k[1],v[0],len(v[1])] temp_v = 0 # finding highest number of complaints filed against one company for that product and year. for v_ in v[1].values(): if v_>temp_v: temp_v = v_ # calculating highest percentage (rounded to the nearest whole number) of total complaints filed against one company for that product and year ratio = int(Decimal((temp_v/v[0])*100).to_integral_value(rounding=ROUND_HALF_UP)) row.append(ratio) # writing to the csv file row by row writer.writerow(row) print('Completed')
c3625fd73193cbcbc96060b39e37b3b9a9104828
Bn-com/myProj_octv
/myset_scripts/ttteeemmm.py
97
3.515625
4
abc = "ABCcdedDD" print(abc.lower()) print(abc.swapcase()) print(abc.title()) print(abc.upper())
ad847ca987ab258b897d0d436a537863b9aeefd5
yangzhaonan18/detect_traffic_light
/kmeans.py
2,705
3.640625
4
# -*- coding=utf-8 -*- # K-means 图像分割 连续图像分割 (充分利用红绿灯的特点) import cv2 import matplotlib.pyplot as plt import numpy as np def seg_kmeans_color(img, k=2): # 变换一下图像通道bgr->rgb,否则很别扭啊 h, w, d = img.shape # (595, 1148, 3) # 0.47 聚类的时间和图像的面积大小成正比,即与图像的点数量成正比。 b, g, r = cv2.split(img) img = cv2.merge([r, g, b]) # 3个通道展平 img_flat = img.reshape((img.shape[0] * img.shape[1], 3)) # 一个通道一列,共三列。每行都是一个点。 img_flat = np.float32(img_flat) # print("len of img_flat = ", len(img_flat)) # 迭代参数 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TermCriteria_MAX_ITER, 20, 0.5) flags = cv2.KMEANS_RANDOM_CENTERS # 聚类 compactness, labels, centers = cv2.kmeans(img_flat, k, None, criteria, 10, flags) # print(" len of labels = ", len(labels)) # print(labels) # 每个点的标签 # print(centers) # 两类的中心,注意是点的值,不是点的坐标 labels = np.squeeze(labels) img_output = labels.reshape((img.shape[0], img.shape[1])) L1 = max(int(img.shape[1] / 4), 2) # 当图像只有四个像素时, L1等于1 会出现-1:的异常异常,所以需要改为2, # 取每个四个角上的点 boundary00 = np.squeeze(img_output[0:L1, 0: L1]. reshape((1, -1))) boundary01 = np.squeeze(img_output[0:L1, - L1:]. reshape((1, -1))) boundary10 = np.squeeze(img_output[- L1:, 0:L1]. reshape((1, -1))) boundary11 = np.squeeze(img_output[- L1:, - L1-1]. reshape((1, -1))) # 取中间一个正方形内的点 inter = img_output[L1: -L1, L1: -L1] boundary_avg = np.average(np.concatenate((boundary00, boundary01, boundary10, boundary11), axis=0)) inter_avg = np.average(inter) print("boundary_avg", boundary_avg) print("inter_avg", inter_avg) if k == 2 and boundary_avg > inter_avg: # 如果聚类使得边缘类是1,即亮的话,需要纠正颜色(所有的标签)。 img_output = abs(img_output - 1) # 将边缘类(背景)的标签值设置为0,中间类(中间类)的值设置为1. img_output = np.array(img_output, dtype=np.uint8) # jiang return img_output if __name__ == '__main__': img = cv2.imread('C:\\Users\\qcdz-003\\Pictures\\light\\007.jpg', cv2.IMREAD_COLOR) img_output = seg_kmeans_color(img, k=2) # 2 channel picture # print(img_output.shape) # (244, 200) # 显示结果 plt.subplot(121), plt.imshow(img), plt.title('input') plt.subplot(122), plt.imshow(img_output, 'gray'), plt.title('kmeans') plt.show()
84b65a981960d7895747edd6e9090df0f34c71e7
hoylemd/practice
/pattern_matching/pattern_matching.py
837
3.890625
4
import argparse import operator # set up the args parser parser = argparse.ArgumentParser(description='This is a script to find all positions of a substring in a string') parser.add_argument("file", help="The file to operate on") args = parser.parse_args() # open the file and read it f = open(args.file) input_lines = f.readlines() # extract the data pattern = input_lines[0][:-1] string = input_lines[1][:-1] # initialize data and take come metrics start_index = 0 matches = [] string_length = len(string) pattern_length = len(pattern) # check every possible location for the string # this is not optimal while start_index < string_length: if string[start_index:start_index + pattern_length] == pattern: matches.append(start_index) start_index += 1 # print out the matches for match in matches: print match,
78d4b7482374fd8a57c06b76b7474b0a373e1d3d
prakashdivyy/advent-of-code-2019
/01/run.py
566
3.546875
4
import math total_part_1 = 0 total_part_2 = 0 filename = 'input.txt' with open(filename,) as file_object: for line in file_object: # Part 1 x_part_1 = int(line,10) res_part_1 = x_part_1 / 3 total_part_1 += math.floor(res_part_1) - 2 # Part 2 x_part_2 = int(line,10) while math.floor(x_part_2 / 3) > 2: res_part_2 = x_part_2 / 3 x_part_2 = math.floor(res_part_2) - 2 total_part_2 += x_part_2 print("Part 1: " + str(total_part_1)) print("Part 2: " + str(total_part_2))
1916ef020df5cb454e7887d2d4bb051d308887e3
sammysun0711/data_structures_fundamental
/week1/tree_height/tree_height.py
2,341
4.15625
4
# python3 import sys import threading # final solution """ Compute height of a given tree Height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a leaf to the root. """ class TreeHeight: def __init__(self, nodes): self.num = len(nodes) self.parent = nodes self.depths = [0] * self.num def path_len(self, node_id): """ Returns path length from given node to root.""" parent = self.parent[node_id] if parent == -1: return 1 if self.depths[node_id]: return self.depths[node_id] self.depths[node_id] = 1 + self.path_len(self.parent[node_id]) return self.depths[node_id] def compute_height(self): """ Computes the tree height.""" return max([self.path_len(i) for i in range(self.num)]) ''' # original solution def compute_height(n, parents): # Replace this code with a faster implementation max_height = 0 for vertex in range(n): height = 0 current = vertex while current != -1: height += 1 current = parents[current] max_height = max(max_height, height) return max_height ''' ''' # alternativ solution, explicit build tree and use recursiv compute_height, # not use cache to store intermediate depth of node,not quick as original solution def build_tree(root_node, nodes): children = [ build_tree(child, nodes) for child, node in enumerate(nodes) if node == root_node ] print(children) return {'key': root_node, 'children':children} def compute_height(tree): return 1 + max((compute_height(child) for child in tree['children']), default=-1) ''' def main(): ''' n = int(input()) parents = list(map(int, input().split())) print(compute_height(n, parents)) ''' input() nodes = list(map(int, input().split())) tree = TreeHeight(nodes) print(tree.compute_height()) # In Python, the default limit on recursion depth is rather low, # so raise it here for this problem. Note that to take advantage # of bigger stack, we have to launch the computation in a new thread. sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size threading.Thread(target=main).start()
0723f91d492b9e11767bc6b5a019977ed0f3eb73
kbtony/my-teleprompt
/src/teleprompter/run.py
4,560
3.84375
4
import csv import sys from datetime import datetime from datetime import timedelta from datetime import timezone USAGE = f"usage: python {sys.argv[0]} file_name.csv datetime" class CommandLine: def __init__(self, argv): # More than two cmd arguments if len(argv) > 3: print("error: at most two command line arguments") raise SystemExit(USAGE) # Two cmd arguments: filename, datetime elif len(argv) == 3: self.filename = argv[1] self.query = argv[2] # One cmd argument: filename elif len(argv) == 2: self.filename = argv[1] self.query = str(datetime.now().astimezone()) # No cmd arguments else: print("error: the following arguments are required: filename") raise SystemExit(USAGE) # Read the input csv file def read_file(filename: str): rows = [] try: with open(filename, 'r', encoding='ISO-8859-1') as csvfile: # Creating a csv reader object csvreader = csv.reader(csvfile) # Skip first row (field names) next(csvreader, None) # Extracting each data row one by one for row in csvreader: rows.append(row) return rows except IOError: print("Error: can't find file or read data") # Convert utcoffset into seconds def utcoffset_to_seconds(time: str): hours = int(time[:2]) if len(time) == 5: minutes = int(time.split(":")[1]) elif len(time) == 4: minutes = int(time[2:]) else: minutes = 0 return hours*3600 + minutes*60 # Generate a datetime object in UTC (zero UTC offset) class Query: def __init__(self, query: str): # Record the timezone (before or after UTC) self.early = True # Record the UTC offset in seconds self.second = 0 if query[len(query) - 1] == 'Z': self.date = datetime.fromisoformat(query[:-1]) elif '+' in query: self.time = query.split("+")[1] self.second = utcoffset_to_seconds(self.time) self.date = datetime.fromisoformat(query.split("+")[0]) - timedelta(seconds=self.second) else: # Offset is right after the third "-" self.time = query.split("-")[3] self.second = utcoffset_to_seconds(self.time) self.date = datetime.fromisoformat(query.split("+")[0]) + timedelta(seconds=self.second) self.early = False self.date = self.date.replace(tzinfo=None) self.check = "" + str(self.date.day) + "/" + str(self.date.month) + "/" + str(self.date.year)[2:] # Retrive information from program list def lookup(program_list, query_date, check, second, early): for i in range(0, len(program_list)): programs = "" # Matching the UTC start date if (program_list[i][2] == check): # For each programs with correct start date # Create two datetime objects concerning this show, one for start time, one for the end time year = int("20" + program_list[i][2].split("/")[2]) month = int(program_list[i][2].split("/")[1]) day = int(program_list[i][2].split("/")[0]) hour = int(program_list[i][3].split(":")[0]) minute = int(program_list[i][3].split(":")[1]) candidate_start = datetime(year, month, day, hour, minute) offset = timedelta(seconds=int(program_list[i][4])) candidate_end = candidate_start + offset # Check whether the query_date is within the playing time of a certain program if (query_date >= candidate_start and query_date < candidate_end): if early: endtime = str((candidate_end + timedelta(seconds=second)).time()) else: endtime = str((candidate_end - timedelta(seconds=second)).time()) programs = "[{}] That was {}, up next is {} which is rated {} and coming up later is {}."\ .format(endtime[:5],program_list[i][0] ,program_list[i + 1][0], program_list[i + 1][1], program_list[i + 2][0]) return programs break def main(): user_input = CommandLine(sys.argv) program_list = read_file(user_input.filename) my_query = Query(user_input.query) result = lookup(program_list, my_query.date, my_query.check, my_query.second, my_query.early) print(result) if __name__=="__main__": main()
61dd1f00de80a02605fdab226828683769b6bf96
araceli24/Ejercicios-Python
/Modificar.py
667
3.5
4
lista = [29, -5, -12, 17, 5, 24, 5, 12, 23, 16, 12, 5, -12, 17] def modificar(l): l = list(set(l)) # Borrar los elementos duplicados (recrea la lista a partir de un nuevo diccionario) l.sort(reverse=True) # Ordenar la lista de mayor a menor for i,n in enumerate(l): # Eliminar todos los números impares if n%2 != 0: del( l[i] ) suma = sum(l) # Realizar una suma de todos los números que quedan l.insert(0, suma) # Añadir como primer elemento de la lista la suma realizada return l # Devolver la lista modificada nueva_lista = modificar(lista) print( nueva_lista[0] == sum(nueva_lista[1:]) )
95ef4825c2a198c3ebabcdb5a26e4328ab4bb4ed
xudalin0609/leet-code
/dynamic/generateTrees.py
887
4.09375
4
""" Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. Example: Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def generateTrees(self, n): for i in range(n): self.__helper(left=i-1, right=i+1) def __helper(self, left, right): while left < right:
83176af41a32baa87bf1ce06b002e1d5c82865f4
xudalin0609/leet-code
/BinarySearch/findPeek.py
1,335
3.75
4
#LintCode 75 """ 75. 寻找峰值 中文English 你给出一个整数数组(size为n),其具有以下特点: 相邻位置的数字是不同的 A[0] < A[1] 并且 A[n - 2] > A[n - 1] 假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1],返回数组中任意一个峰值的位置。 样例 样例 1: 输入: [1, 2, 1, 3, 4, 5, 7, 6] 输出: 1 or 6 解释: 返回峰顶元素的下标 样例 2: 输入: [1,2,3,4,1] 输出: 3 挑战 Time complexity O(logN) 注意事项 数组保证至少存在一个峰 如果数组存在多个峰,返回其中任意一个就行 数组至少包含 3 个数 """ class Solution: """ @param: A: An integers array. @return: return any of peek positions. """ def findPeak(self, A): # write your code here start, end = 1, len(A) - 2 while start < end - 1: mid = (start + end) >> 1 if A[mid] > A[mid - 1] and A[mid] > A[mid + 1]: return mid elif A[mid] < A[mid + 1]: start = mid else: end = mid if A[start] >= A[end]: return start else: return end if __name__ == "__main__": print(Solution().findPeak([1,2,1,3,4,5,7,6])) print(Solution().findPeak([1,2,3,4,1]))
740a31e63edbde67c2add9e33219f5616c5af689
xudalin0609/leet-code
/BFS/sequenceReconstruction.py
2,434
3.828125
4
""" 605. 序列重构 中文English 判断是否序列 org 能唯一地由 seqs重构得出. org是一个由从1到n的正整数排列而成的序列,1<=n<=10^4​ 。 重构表示组合成seqs的一个最短的父序列 (意思是,一个最短的序列使得所有 seqs里的序列都是它的子序列). 判断是否有且仅有一个能从 seqs重构出来的序列,并且这个序列是org。 样例 例1: 输入:org = [1,2,3], seqs = [[1,2],[1,3]] 输出: false 解释: [1,2,3] 并不是唯一可以被重构出的序列,还可以重构出 [1,3,2] 例2: 输入: org = [1,2,3], seqs = [[1,2]] 输出: false 解释: 能重构出的序列只有 [1,2]. 例3: 输入: org = [1,2,3], seqs = [[1,2],[1,3],[2,3]] 输出: true 解释: 序列 [1,2], [1,3], 和 [2,3] 可以唯一重构出 [1,2,3]. 例4: 输入:org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]] 输出:true """ import collections class Solution: """ @param org: a permutation of the integers from 1 to n @param seqs: a list of sequences @return: true if it can be reconstructed only one or false """ def sequenceReconstruction(self, org, seqs): graph = self.build_graph(seqs) return org == self.topo_sort(graph) def build_graph(self, seqs): graph = {} for seq in seqs: for num in seq: graph[num] = set() for seq in seqs: for i in range(1, len(seq)): graph[seq[i - 1]].add(seq[i]) return graph def topo_sort(self, graph): indegrees = { node: 0 for node in graph } for node in graph: for neighbor in graph[node]: indegrees[neighbor] += 1 queue = [] for node in graph: if indegrees[node] == 0: queue.append(node) topo_order = [] while queue: if len(queue) > 1: return node = queue.pop() topo_order.append(node) for neighbor in graph[node]: indegrees[neighbor] -= 1 if indegrees[neighbor] == 0: queue.append(neighbor) if len(topo_order) == len(graph): print(topo_order, graph) return topo_order return print(Solution().sequenceReconstruction([1], []))
8178aa5e0cc682bec6b3935fa7eadf2c1c9bb3fa
xudalin0609/leet-code
/Greedy/canCompleteCircuit.py
1,549
3.5625
4
# LintCode 187 """ 187. 加油站 中文English 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第_i_个加油站前往第_i_+1个加油站需要消耗汽油cost[i]。 你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。 求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。 样例 样例 1: 输入:gas[i]=[1,1,3,1],cost[i]=[2,2,1,1] 输出:2 样例 2: 输入:gas[i]=[1,1,3,1],cost[i]=[2,2,10,1] 输出:-1 挑战 O(n)时间和O(1)额外空间 注意事项 数据保证答案唯一。 """ class Solution: """ @param gas: An array of integers @param cost: An array of integers @return: An integer """ def canCompleteCircuit(self, gas, cost): if sum(gas) - sum(cost) < 0: return -1 tol_remain = gas[0] - cost[0] start_site = [0, tol_remain] for site_loction in range(len(gas)): tol_remain = tol_remain + gas[site_loction] - cost[site_loction] if tol_remain < start_site[1]: start_site = [site_loction, tol_remain] return start_site[0] + 1 if __name__ == "__main__": print(Solution().canCompleteCircuit([1,1,3,1], [2,2,10,1])) print(Solution().canCompleteCircuit([1,1,3,1], [2,2,1,1])) # 2 print(Solution().canCompleteCircuit([1,2,3,4,5], [3,4,5,1,2])) print(Solution().canCompleteCircuit([2,0,1,2,3,4,0],[0,1,0,0,0,0,11] )) # 1
ae456f697158e53e2a6a806a6344757247fd1e23
xudalin0609/leet-code
/Greedy/canPlaceFlowers.py
1,176
4
4
# 605 """ 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。 示例 1: 输入: flowerbed = [1,0,0,0,1], n = 1 输出: True 示例 2: 输入: flowerbed = [1,0,0,0,1], n = 2 输出: False 注意: 数组内已种好的花不会违反种植规则。 输入的数组长度范围为 [1, 20000]。 n 是非负整数,且不会超过输入数组的大小。 """ class Solution: def canPlaceFlowers(self, flowerbed, n): can_place = 0 flowerbed.insert(0,0) flowerbed.append(0) for i in range(1, len(flowerbed)-1): if flowerbed[i-1] == 0 and flowerbed[i+1] == 0 and flowerbed[i] == 0: flowerbed[i] = 1 can_place += 1 return can_place >= n if __name__ == "__main__": print(Solution().canPlaceFlowers([1,0,0,0, 1], 2))
e3b9ee8b7a645084e7430185c65db3e59d097718
xudalin0609/leet-code
/DFS/wordSearchII.py
2,763
3.84375
4
# LintCode 132 """ 132. 单词搜索 II 中文English 给出一个由小写字母组成的矩阵和一个字典。找出所有同时在字典和矩阵中出现的单词。 一个单词可以从矩阵中的任意位置开始,可以向左/右/上/下四个相邻方向移动。一个字母在一个单词中只能被使用一次。且字典中不存在重复单词 样例 样例 1: 输入:["doaf","agai","dcan"],["dog","dad","dgdg","can","again"] 输出:["again","can","dad","dog"] 解释: d o a f a g a i d c a n 矩阵中查找,返回 ["again","can","dad","dog"]。 样例 2: 输入:["a"],["b"] 输出:[] 解释: a 矩阵中查找,返回 []。 挑战 使用单词查找树来实现你的算法 """ DIRECTIONS = [(0, -1), (0, 1), (-1, 0), (1, 0)] class Solution: """ @param board: A list of lists of character @param words: A list of string @return: A list of string """ def wordSearchII(self, board, words): if not board: return [] words_set = set(words) prefix_string = set([]) for word in words: for i in range(len(word)): prefix_string.add(word[:i+1]) print(prefix_string) results = set([]) for x in range(len(board)): for y in range(len(board[x])): self.search(board, x, y, board[x][y], prefix_string, words_set, results, set([(x, y)])) return list(results) def search(self, board, x, y, subtring, prefix_string, words_set, results, visited): if subtring not in prefix_string: return if subtring in words_set: results.add(subtring) for delta_x, delta_y in DIRECTIONS: x_ = x + delta_x y_ = y + delta_y if not self.is_inside(x_, y_, board): continue if (x_, y_) in visited: continue visited.add((x_, y_)) self.search(board, x_, y_, subtring + board[x_][y_], prefix_string, words_set, results, visited) visited.remove((x_, y_)) return results def is_inside(self, x, y, board): return 0 <= x < len(board) and 0 <= y < len(board[0]) if __name__ == "__main__": # print(Solution().wordSearchII(["doaf", "agai", "dcan"], [ # "dog", "dad", "dgdg", "can", "again"])) print(Solution().wordSearchII( ["b", "a", "b", "b", "a"], ["babbab", "b", "a", "ba"] ))
014009ae4f7e48fe843dd5dc02104ffbf887fb52
xudalin0609/leet-code
/BFS/numIslands.py
2,072
3.8125
4
# LintCode 433 """ 433. 岛屿的个数 中文English 给一个 01 矩阵,求不同的岛屿的个数。 0 代表海,1 代表岛,如果两个 1 相邻,那么这两个 1 属于同一个岛。我们只考虑上下左右为相邻。 样例 样例 1: 输入: [ [1,1,0,0,0], [0,1,0,0,1], [0,0,0,1,1], [0,0,0,0,0], [0,0,0,0,1] ] 输出: 3 样例 2: 输入: [ [1,1] ] 输出: 1 """ import collections class Solution: """ @param grid: a boolean 2D matrix @return: an integer """ DIRECTIONS = [(1, 0), (0, -1), (-1, 0), (0, 1)] def numIslands(self, grid): if not grid or len(grid[0]) == 0: return 0 islands = 0 visited = set() for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] != 0 and (i, j) not in visited: self.bfs(grid, i, j, visited) islands += 1 return islands def bfs(self, grid, x, y, visited): # queue = collections.deque([(x, y)]) queue = [(x, y)] visited.add((x, y)) while queue: # x, y = queue.popleft() x, y = queue.pop() for delta_x, delta_y in self.DIRECTIONS: next_x = x + delta_x next_y = y + delta_y if not self.is_valid(grid, next_x, next_y, visited): continue visited.add((next_x, next_y)) queue.append((next_x, next_y)) def is_valid(self, grid, x, y, visited): if (0 <= x <= len(grid) - 1) and (0 <= y <= len(grid[x]) - 1) and grid[x][y] == 1 and (x, y) not in visited: return True return False if __name__ == "__main__": print(Solution().numIslands([ [1,1,0,0,0], [0,1,0,0,1], [0,0,0,1,1], [0,0,0,0,0], [0,0,0,0,1] ]))
310be24ce75fad3d656397284eaf5fbbc9f70784
xudalin0609/leet-code
/DivideAndConquer/flatten.py
1,974
4.03125
4
# LintCode 453 """ 453. 将二叉树拆成链表 中文English 将一棵二叉树按照前序遍历拆解成为一个 假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。 样例 样例 1: 输入:{1,2,5,3,4,#,6} 输出:{1,#,2,#,3,#,4,#,5,#,6} 解释: 1 / \ 2 5 / \ \ 3 4 6 1 \ 2 \ 3 \ 4 \ 5 \ 6 样例 2: 输入:{1} 输出:{1} 解释: """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten(self, root): self.flatten_and_return_last_node(root) # restructure and return last node in preorder def flatten_and_return_last_node(self, root): if root is None: return None left_last = self.flatten_and_return_last_node(root.left) right_last = self.flatten_and_return_last_node(root.right) # connect if left_last is not None: left_last.right = root.right root.right = root.left root.left = None return right_last or left_last or root class Solution: def flatten(self, root: 'TreeNode') -> 'None': """ Do not return anything, modify root in-place instead. """ if not root: return stack = collections.deque([root]) while stack: node = stack.pop() if node.right: stack.append(node.right) if node.left: stack.append(node.left) node.left = None if stack: node.right = stack[-1] else: node.right = None
5e0b1671e4a00faa1c0481ea461ffaa089c30d5e
xudalin0609/leet-code
/DivideAndConquer/findKthLargest.py
1,560
4
4
""" Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. """ class Solution: def findKthLargest(self, nums, k): self.k = k self.nums = nums return self.__findKthLargest(nums, 0, len(nums) - 1) def __findKthLargest(self, nums, left, right): pi = self.getKth(nums, left, right) if pi > self.k - 1: res = self.__findKthLargest(nums, left, pi - 1) elif pi < self.k - 1: res = self.__findKthLargest(nums, pi + 1, right) else: return nums[pi] return res def getKth(self, arr, low, high): j = low-1 # index of smaller element pivot = arr[high] # pivot for i in range(low, high): # If current element is smaller than or # equal to pivot if arr[i] >= pivot: # increment index of smaller element j += 1 arr[i], arr[j] = arr[j], arr[i] arr[j+1], arr[high] = arr[high], arr[j+1] return j+1 if __name__ == "__main__": print(Solution().findKthLargest([3, 2, 1, 5, 6, 4], 2)) print(Solution().findKthLargest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)) print(Solution().findKthLargest([-1, 2, 0], 1))
6cca45c1943ad0fa138ae0e5dcf331aa54aba5b1
xudalin0609/leet-code
/BFS/searchNode.py
2,303
4.09375
4
""" 618. 搜索图中节点 中文English 给定一张 无向图,一个 节点 以及一个 目标值,返回距离这个节点最近 且 值为目标值的节点,如果不能找到则返回 NULL。 在给出的参数中, 我们用 map 来存节点的值 样例 例1: 输入: {1,2,3,4#2,1,3#3,1,2#4,1,5#5,4} [3,4,5,50,50] 1 50 输出: 4 解释: 2------3 5 \ | | \ | | \ | | \ | | 1 --4 Give a node 1, target is 50 there a hash named values which is [3,4,10,50,50], represent: Value of node 1 is 3 Value of node 2 is 4 Value of node 3 is 10 Value of node 4 is 50 Value of node 5 is 50 Return node 4 例2: 输入: {1,2#2,1} [0,1] 1 1 输出: 2 注意事项 保证答案唯一 """ """ Definition for a undirected graph node class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] """ import collections class Solution: """ @param: graph: a list of Undirected graph node @param: values: a hash mapping, <UndirectedGraphNode, (int)value> @param: node: an Undirected graph node @param: target: An integer @return: a node """ # def searchNode(self, graph, values, node, target): # if len(graph)==0 or len(values)==0: # return None # q=collections.deque() # Set=set() # q.append(node) # Set.add(node) # while len(q): # if values[q[0]] == target:#找到结果 # return q[0]; # for neighbor in q[0].neighbors:#遍历每个点的所有边 # #判断此点是否出现过 # if neighbor not in Set: # q.append(neighbor) # Set.add(neighbor) # q.popleft() # return None def searchNode(self, graph, values, node, target): if not graph: return queue = collections.deque([node]) used = set() used.add(node) while queue: sub_node = queue.popleft() if values[sub_node] == target: return sub_node for neighbor in sub_node.neighbors: queue.append(neighbor) used.add(neighbor) return # {1,2,3,4#2,1,3#3,1#4,1,5#5,4} # [3,4,5,50,50] # 1 # 50
b4c38e0f4f0446c2bb67bdb844f51ce3263732c7
xudalin0609/leet-code
/DivideAndConquer/closestValue.py
2,799
3.9375
4
# LintCode 900 """ 900. 二叉搜索树中最接近的值 中文English 给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值 样例 样例1 输入: root = {5,4,9,2,#,8,10} and target = 6.124780 输出: 5 解释: 二叉树 {5,4,9,2,#,8,10},表示如下的树结构: 5 / \ 4 9 / / \ 2 8 10 样例2 输入: root = {3,2,4,1} and target = 4.142857 输出: 4 解释: 二叉树 {3,2,4,1},表示如下的树结构: 3 / \ 2 4 / 1 注意事项 给出的目标值为浮点数 我们可以保证只有唯一一个最接近给定值的节点 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the given BST @param target: the given target @return: the value in the BST that is closest to the target """ def closestValue(self, root, target): # write your code here closest_value = root.val left_value = self.find_closest_val(root.left, target, closest_value) right_value = self.find_closest_val(root.right, target, closest_value) return self.get_closer_val(left_value, right_value, target) def find_closest_val(self, node, target, closest_value): if node is None: return closest_value left_value = self.find_closest_val(node.left, target, closest_value) right_value = self.find_closest_val(node.right, target, closest_value) if self.get_closer_val(left_value, right_value, target) == left_value: closest_value = self.get_closer_val(left_value, closest_value, target) else: closest_value = self.get_closer_val(right_value, closest_value, target) return closest_value def get_closer_val(self, val1, val2, target): if abs(val1 - target) > abs(val2 - target): return val2 return val1 class Solution: """ @param root: the given BST @param target: the given target @return: the value in the BST that is closest to the target """ def closestValue(self, root, target): if root is None: return(9999999999) leftcloset = self.closestValue(root.left, target) rightcloset = self.closestValue(root.right, target) root_diff = abs(root.val - target) leftdiff = abs(leftcloset -target ) rightdiff = abs(rightcloset -target ) if root_diff == min(root_diff,leftdiff, rightdiff): return root.val elif leftdiff == min(root_diff, leftdiff, rightdiff): return leftcloset else: return rightcloset
d49a28a9653203145baf58365b4c7e4861e6b01b
ryan-aday/adayR
/20_cw/app.py
1,675
3.65625
4
from functools import reduce from collections import Counter import itertools import operator def most_common(L): # get an iterable of (item, iterable) pairs SL = sorted((x, i) for i, x in enumerate(L)) # print 'SL:', SL groups = itertools.groupby(SL, key=operator.itemgetter(0)) # auxiliary function to get "quality" for an item def _auxfun(g): item, iterable = g count = 0 min_index = len(L) for _, where in iterable: count += 1 min_index = min(min_index, where) # print 'item %r, count %r, minind %r' % (item, count, min_index) return count, -min_index # pick the highest-count/earliest item return max(groups, key=_auxfun)[0] fd = open('data.txt', 'r') book = fd.read().lower() count=0 fd.close() print("Count of proletariat: " + str(book.count('proletariat'))) print("Count of 'working class': " + str(book.count('working class'))) alphabet = "abcdefghijklmnopqrstuvwxyz" words = [] current = "" for char in book: if char in alphabet: current+=char elif current!="": words.append(current) current="" #print(words) # count=0 # for x in words: # if x=="proletariat": # count+=1 # print(count) common_words = ["the", "and", "to", "by", "is", "in", "of", "a", "that", "it", "them"] max_word = "" max_count = 0 for x in words: if words.count(x)>max_count and x not in common_words: max_count = words.count(x) max_word = x list=[[x,words.count(x)] for x in words if x not in common_words] #print(most_common(list)) word=[x for x in list if x[1]==max_count] w=word[0][0] wc=word[0][1] print("Max uncommon word: " + str(w) + "; Count: " + str(wc))
4cc92252d90ac9677998ec3669b3bd7a35bb8d10
alxthedesigner/cloud_application_example
/word_number_app.py
1,368
3.84375
4
from flask import Flask from flask import request application = Flask(__name__) #App Instance created @application.route("/") #When URL ends in '/', execute method def home(): return WORDHTML WORDHTML = """ <html><body> <h2>Word and Number Game</h2> <form action="/game"> Enter a word: <input type='text' name='wrd'><br> Enter a number <input type='text' name='num'><br> <input type='submit' value='Continue'> </form> </body></html>""" @application.route("/game") def infoDescription(): word = request.args.get('wrd', '') number = request.args.get('num', '') doubled = number*2 nummsg1 = "The doubled value of", number, "is" + doubled wordL = len(word) wordmsg1 = "Your word has", wordL, "letters" backwrd = word[::-1] if word == backwrd: wordmsg2 = "Your word is a palindrome! Your word spelled backwards is" + backwrd else: wordmsg2 = "Your word spelled backwards is" + backwrd return DESCRIPTIONHTML.format(nummsg1, wordmsg1, wordmsg2) DESCRIPTIONHTML = """ <html><body> <h2>Results!</h2> <p> <br>{0} <br>{1} <br>{2} </p> </body></html> """ if __name__ == "__main__": application.run(host="0.0.0.0", debug=True) # run flask App Instance
c5ac3685195f48a4da04cd71e2ed8202c375ac28
Teghfo/python_workhosp_zemestan98_mapsa
/J6/my_pickle.py
1,021
3.71875
4
import pickle class Book: def read_data(self): self.title = input('Enter Book tile: ') if not self.title: return self.author = input('Enter Author name: ') self.page_count = input('Enter page count: ') self.borrow_history = [] def add_borrow_history(self, username): self.borrow_history.append(username) def print_book_data(self): print(f'title: {self.title} author: {self.author} title: {self.title}') print('----------------------write data-------------------') f = open('boooooks', 'wb') book = Book() book.read_data() while book.title: pickle.dump(book, f) book.read_data() print('all books saved on file boooooks') f.close() print('---------------------------read data-------------------') f = open('boooooks', 'rb') rogin = pickle.load(f) print(rogin) while True: rogin.print_book_data() try: rogin = pickle.load(f) except: print('Finish!') break print('va TAMAM!') f.close()
853c4b8d92dd31f672cdc1f15cb0deedc852c961
desperadoespoir/TheoriesDesGraphes-LangagesNaturels
/tp2/automate.py
1,655
3.921875
4
class Automate(object): """Une class automate qui permet de lire des solutions on peut y ajouter une regle on peut aussi resoudre avec la fonction solve et un mot de passe """ END = -1 NOT_FOUND = 0 START = "" def __init__(self, name): self.name = name self.regles = {} def __lshift__(self, regle): passed_equal = False first_char = True key = "" result = "" for char in regle: if char == '=': passed_equal, first_char = True, True elif first_char: first_char = not first_char elif not passed_equal: key += char else: result += char if (key not in self.regles) or (self.regles[key] == Automate.END): self.regles[key] = [result] else: self.regles[key] += [result] self.regles[result] = Automate.END def __contains__(self, item): return item in self.regles def __getitem__(self, key): return self.regles[key] def solve(self, string): i = 0 substr = string[i] while substr != Automate.END and substr != Automate.NOT_FOUND: if substr in self.regles: if self.regles[substr] == Automate.END: substr = Automate.END elif i >= len(string): substr = Automate.NOT_FOUND else: i += 1 substr += string[i] else: substr = Automate.NOT_FOUND return substr != Automate.NOT_FOUND
1e26f26d4d308a9a9ac1c8f9975b459b945ce315
Htrams/Leetcode
/binary_search_tree_iterator.py
1,101
4.03125
4
# My Rating = 2 # https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/570/week-2-december-8th-december-14th/3560/ # 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 BSTIterator: def __init__(self, root: TreeNode): def inOrderTraversal(output,node): if node.left is not None: output.extend(inOrderTraversal([],node.left)) output.append(node.val) if node.right is not None: output.extend(inOrderTraversal([],node.right)) return output self.output=inOrderTraversal([],root) self.currentNode = -1 def next(self) -> int: self.currentNode += 1 return self.output[self.currentNode] def hasNext(self) -> bool: return self.currentNode+1<len(self.output) # Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
b07d3973639dd0b42409027ff1ed2e31aace33cf
Htrams/Leetcode
/matrix_diagonal_sum.py
621
3.9375
4
# My Rating = 1 # https://leetcode.com/contest/biweekly-contest-34/problems/matrix-diagonal-sum/ # Given a square matrix mat, return the sum of the matrix diagonals. # Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: n=len(mat) sum=0 for i in range(n): sum=sum+mat[i][i] for i in range(n): sum=sum+mat[i][n-i-1] if n%2!=0: sum=sum-mat[n//2][n//2] return sum
f02f36b8bab69dcaef3240ae84600a3092f720ae
Htrams/Leetcode
/flipping_an_image.py
854
3.875
4
# My Rating = 1 # https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3526/ # Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. # To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally # results in [0, 1, 1]. # To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for i in range(len(A)): for j in range((len(A[0])-1)//2+1): temp = 1- A[i][j] A[i][j] = 1- A[i][len(A[0])-j-1] A[i][len(A[0])-j-1] = temp return A
6ab534dbbc70e049b062fd0f93c43f578531e8fa
Htrams/Leetcode
/psuedo-palindromic_paths_in_a_binary_tree.py
1,489
3.859375
4
# My Rating = 1 # https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/573/week-5-december-29th-december-31st/3585/ # Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic # if at least one permutation of the node values in the path is a palindrome. # Return the number of pseudo-palindromic paths going from the root node to leaf nodes. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: def graphTraversal(node,record): record[node.val-1] += 1 temp = 0 if node.left is not None: temp += graphTraversal(node.left,record) if node.right is not None: temp += graphTraversal(node.right,record) if node.left is None and node.right is None: flag=False odds = 0 for ele in record: if ele%2==1: odds+=1 if odds>1: flag = True break if not flag: temp = 1 record[node.val-1] -= 1 return temp record=[0]*9 return graphTraversal(root,record)
d7b224fc94c116eb466349f05f2657f0cd0fc27a
Htrams/Leetcode
/reverse_string.py
308
3.5
4
# My Rating = 1 class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ length=len(s) for i in range(length//2): temp=s[i] s[i]=s[length-i-1] s[length-i-1]=temp
7bb08a8b4b5963ff4fdf46f7a62e30959e74aac0
Htrams/Leetcode
/swapping_nodes_in_a_linked_list.py
1,676
3.71875
4
# My Rating = 2 # https://leetcode.com/contest/weekly-contest-223/problems/swapping-nodes-in-a-linked-list/ # The following code interchanges the nodes, instead of the values in the node. # You are given the head of a linked list, and an integer k. # Return the head of the linked list after swapping the values # of the kth node from the beginning and the kth node from the # end (the list is 1-indexed). # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: store = [] temp = head while temp is not None: store.append(temp) temp = temp.next leng = len(store) k=min(k,leng-k+1) if leng%2==1 and k==leng//2+1: return head # Edge Cases if k==1: if leng == 2: store[1].next = store[0] store[0].next = None return store[1] else: store[-2].next = store[0] store[0].next = None store[-1].next = store[1] return store[-1] if leng%2==0 and k==leng//2: store[k-2].next = store[k] store[k].next = store[k-1] store[k-1].next = store[k+1] return head # Swap nodes at k-1 and len(store)-k store[k-2].next = store[leng-k] store[leng-k].next = store[k] store[leng-k-1].next = store[k-1] store[k-1].next = store[leng-k+1] return head
c14defaa309c4ab8868ae7c756bd89aeeb5bf678
grsind19/Pythondeveloper
/2. Learning Python/11. Fileaccess.py
256
3.53125
4
def main(): # f = open('textfile.txt','w+') # for i in range(10): # f.write("this is line "+str(i) + "\r\n") g = open('textfile.txt','r') if g.mode == 'r': contents = g.read() print(contents) if __name__ == "__main__": main()
3ef54f4dcf0751f1bc2d4be3bc387910c2e0330d
grsind19/Pythondeveloper
/1. Programmingfoundationsandalsogithms/10. Quicksort.py
840
3.734375
4
items=[6, 20, 8, 19, 56, 23, 87, 41, 49, 53] def quickSort(dataset, first, last): if first < last: pivotrIdx = partition(dataset, first, last) quickSort(dataset, first, pivotrIdx-1) quickSort(dataset, pivotrIdx+1, last) def partition(dataset, first, last): pivotValue = dataset[first] lower = first+1 upper = last done = False while not done: while pivotValue >= dataset[lower] and upper >= lower: lower +=1 while pivotValue <= dataset[upper] and upper >= lower: upper -= 1 if upper < lower: done = True else: temp = dataset[lower] dataset[lower] = dataset[upper] dataset[upper] = temp temp = dataset[first] dataset[first] = dataset[upper] dataset[upper] = temp return upper print(items) quickSort(items,0, len(items)-1) print(items)
fb2e544ffcccaacad953cfcba321bf757af6ecef
grsind19/Pythondeveloper
/5. PythonstandardLib/8. Type.py
167
3.5625
4
# type # Instance class Car: pass class Truck(Car): pass c = Car() t = Truck() print(type(c)) print(type(t)) print(isinstance(c,Car)) print(isinstance(t,Car))
683673bcb322193b98900c5dd93ec07b14f5eb8a
tron135/python_practise
/even odd.py
137
4.21875
4
number = int(input('Enter any number: ')) if(number%2 == 0): print('The Number is even.') else: print('The Number is odd.')
c5d87c6d8317f501cb862fb0a8bc30b16868e759
tron135/python_practise
/unlucky number.py
202
3.875
4
for i in range(1,21): if i == 4 or i == 13: s = str(i) + " is unlucky !!!!" print(s) elif i % 2 == 0: t = str(i) + " is even !!" print(t) else: u = str(i) + " is odd !!" print(u)
adc39c22e430ce632ebcb644797ef2addd9f8553
hyunlove12/20191005
/dlearn/digits/__init__.py
1,242
3.671875
4
import matplotlib.pyplot as plt from digits.hand_writing import HandWriting if __name__ == '__main__': def print_menu(): test = ['asdfsadf', 'asdgsad', 'asdf'] print(test) #print(test[:3, 1]) t = [2 == 2] print(t) print('0, EXIT') print('1, 손글씨 인식') print('2, 고양이 모자이크') #XML파일이 없으면 얼굴 특정 실패 print('3, 얼굴 모자이크') print('4, LENA 이미지 인식') print('5, FASHION 이미지 인식') print('6, 이미지 편집하기') return input('CHOOSE ONE \n') while 1: menu = print_menu() if menu == '0': print('EXIT') break elif menu == '1': m = HandWriting() m.read_file() elif menu == '2': m = HandWriting() m.learning() elif menu == '3': m = HandWriting() fname = './data/my4.png' print('테스트') print() print(m.test(fname)) elif menu == '4': pass elif menu == '5': pass elif menu == '6': pass elif menu == '7': pass
7a75cd6d39e5329b1226ddf851478f341cc163bc
m-hollow/deeper_dungeons
/old_files (archive)/main.py
45,747
3.671875
4
import time from random import randint from random import choice import copy # define game objects class GameSettings(): """Define game settings""" def __init__(self): self.grid_size = 5 self.starting_gold = 10 self.difficulty = 1 def user_settings_change(self): msg = 'Choose the size of the dungeon grid: ' size_choice = int(input(msg)) self.grid_size = size_choice class GameGrid(): """Creates a grid object for the game of variable size""" def __init__(self, settings, player): self.settings = settings self.player = player self.row = self.settings.grid_size self.col = self.settings.grid_size # question: should floor_level be stored in settings? self.floor_level = 1 # objects constructed as levels advance will increase this number # perhaps that means I should use a __class__ attribute here? self.grid_matrix = self.make_grid() # grid for graphics, containing strings '*' self.all_room_grid = self.generate_rooms() # grid for room data, containing room dictionaries self.create_start() # same as below, adds start on construction self.create_exit() # doesn't need to return anything, just adds the exit on construction self.create_mystic() # one mystic in every dungeon level self.current_room_type = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Type'] # this is a bool and is used to track if current inhabited room was previously visited or not # and yes, you could perform this check by checking the all_room_grid and looking at 'Visited' bool directly. self.room_status = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Visited'] def make_grid(self): # list comprehension to create matrix of the game grid graphics grid_matrix = [[' * ' for x in range(self.col)] for y in range(self.row)] return grid_matrix def update_player_location(self): """updates the grid_matrix to show the X for the player coordinates (and change prev room back to a *)""" self.grid_matrix[self.player.previous_coords[0]][self.player.previous_coords[1]] = ' * ' self.grid_matrix[self.player.player_location[0]][self.player.player_location[1]] = ' X ' def update_current_roomtype(self): """udpate the current_room_type attribute to reflect current player location""" self.current_room_type = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Type'] self.room_status = self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Visited'] # remember, all_room_grid is a list containing multiple lists, and each of THOSE lists contains a bunch of # dictionaries (the room dictionaries, with keys for Type and Visited, etc). # the above code indexes the all_room_grid with format [][][] # first [] - index list inside the main list, e.g. which list do we want inside the main list? # second [] - index that list, e.g. which dictionary do we want inside the list we've chosen? # third [] - index the dictionary by key, giving us the value stored for that key. def generate_rooms(self): """create a room that corresponds to each coordinate in the grid matrix object""" all_room_grid = [] # will become a matrix (a list of lists) containing room dictionaries for r in self.grid_matrix: # r is a list row = [] for c in r: # c is a string ('*'), num of loops will = num of * in list r room_type = self.get_room_type() room = {'Type':room_type, 'Visited':False, 'Post_Note': None} row.append(room) all_room_grid.append(row) # done once for each list (r) in the grid_matrix return all_room_grid def get_room_type(self): """called by generate_rooms function to make one random room""" room_type = '' num = randint(1,8) if num >= 1 and num <= 4: room_type = 'Empty' elif num >= 5 and num <= 7: room_type = 'Monster' elif num == 8: room_type = 'Treasure' return room_type def create_start(self): self.all_room_grid[self.player.player_location[0]][self.player.player_location[1]]['Type'] = 'Start' def create_exit(self): """creates an exit in the room grid and makes sure it doesn't overlap with player start position""" active = True while active: # should I just change the min random number, rather than the complex conditionals in the if below ?? random_x = randint(0, self.row - 1) random_y = randint(0, self.col - 1 ) coords = [random_x, random_y] # makes sure exit 1. does not overlap player 2. is not within 2 rows of the player (this logic needs some work...) if coords != self.player.player_location and abs(coords[0] - self.player.player_location[0]) \ >= 2 and abs(coords[1] - self.player.player_location[1]) >= 1: self.all_room_grid[random_x][random_y]['Type'] = 'Exit' active = False else: pass def create_mystic(self): active = True while active: random_x = randint(0, self.row - 1) random_y = randint(0, self.col - 1) coords = [random_x, random_y] if coords != self.player.player_location and self.all_room_grid[random_x][random_y]['Type'] != 'Exit': self.all_room_grid[random_x][random_y]['Type'] = 'Mystic' active = False else: pass def print_grid(self): """print the visual game grid""" print('\nLV.{}'.format(self.floor_level)) for r in self.grid_matrix: for c in r: print(c, end='') print() # use print('\n' to space out grid further) print() #print('\n{} is located at X'.format(self.player.info['Name'])) def dev_grid_showtypes(self): """for dev testing, not gameplay: show current properties of all rooms""" clear_screen() r = 0 #grid_matrix_copy = self.grid_matrix[:] # doesn't work, does a shallow copy grid_matrix_copy = copy.deepcopy(self.grid_matrix) # modify chars in the deepcopy based on corresponding roomtype in original all_room_grid # incrementing variables r, c used to index (and thereby modify) contents of deepcopy grid for row in self.all_room_grid: c = 0 for col in row: if col['Type'] == 'Empty': grid_matrix_copy[r][c] = ' E ' elif col['Type'] == 'Monster': grid_matrix_copy[r][c] = ' M ' elif col['Type'] == 'Treasure': grid_matrix_copy[r][c] = ' T ' elif col['Type'] == 'Exit': grid_matrix_copy[r][c] = ' @ ' elif col['Type'] == 'Start': grid_matrix_copy[r][c] = ' S ' elif col['Type'] == 'Mystic': grid_matrix_copy[r][c] = ' & ' c += 1 r += 1 # print the dev grid for row in grid_matrix_copy: for val in row: print(val, end = '') print() press_enter() def build_next_dungeon_floor(self): """updates dungeon grid to next floor when player exits previous floor""" # increment various things to make next dungeon more difficult. # update settings file accordingly so monster difficulty scales, etc. class Dice(): """Create a variable sided die that can be rolled""" def __init__(self): self.last_roll = None self.dice_text = '' def roll(self, sides=6): roll = randint(1, sides) self.last_roll = roll return roll def print_roll(self, mods=None): # mods is not actually being used at all text = 'ROLLING...' for c in text: print(c, end='', flush=True) time.sleep(0.06) print(' {}'.format(self.last_roll)) # use lambda here to put 'if mods' inside line? if mods: print('+{}'.format(mods)) class Weapon(): """Generates a weapon object with type and damage""" def __init__(self, name, damage): self.name = name self.damage = damage self.icon = self.get_dam_icon() def modify_weapon(self, add_to_damage): self.name += '++' self.damage += add_to_damage def print_stats(self): print('*** WEAPON INFO ***') #print() print('TYPE{:.>15}'.format(self.name)) print('DAMAGE{:.>13}'.format(self.damage)) def get_dam_icon(self): return '(1d' + str(self.damage) + ')' class Armor(): """only instantiated as an attribute of player class""" def __init__(self, name, armor_class): self.name = name self.armor_class = armor_class def modify_armor(self, add_to_ac): self.name += '++' self.armor_class += add_to_ac def print_stats(self): print('*** ARMOR INFO ***') print('TYPE{:.>14}'.format(self.name)) print('AC{:.>16}'.format(self.ac)) class Player(): """Generates the user character""" def __init__(self, settings): self.settings = settings self.created = False self.dead = False self.info = {'Name':'None', 'Race':''} # starting values for player game attributes self.name = self.info['Name'] self.level = 1 self.hp = 10 # current in game hp amount self.max_hp = 10 # current max hp for player level self.gold = 10 self.exp = 10 # set on creation of player object self.next_level_at = self.get_level_up_val() # determined on creation of player object # checks will need to be done in game loop to see if player's current exp is > than level_up, and if so, # we need to call a level up function AND ALSO call a function to increase 'level_up' attribute to next # setting (so next level-up occurs at higher exp amount, etc). self.dice = Dice() # player items self.potions = [] self.items = ['Torch',] self.weapon = Weapon('Dagger', 4) self.armor = Armor('Leather', 10) # player location on grid. continually updated during gameplay. self.player_location = [(self.settings.grid_size - 1), (int(self.settings.grid_size / 2) - 1)] self.previous_coords = [0,0] def get_level_up_val(self): if self.level == 1: return 100 if self.level == 2: return 220 if self.level == 3: return 350 if self.level > 3: return (2 * self.exp) # think through / clarify this math here. can you use it throughout? def build_player(self): clear_screen() a = input('What is the name of your character? ') b = input('What is the Race of your character? ') self.info['Name'] = a.title() self.info['Race'] = b.title() clear_screen() print('You have successfully created {} the {}.'.format(a.title(), b.title())) print('You will begin with {} Hit Points and {} Gold Pieces.'.format(self.hp, self.gold)) print('\nYou are now ready to start the game!') press_enter() def print_player_info(self): """display all player stats on the screen""" clear_screen() print("# PLAYER INFO #\n") print("Name{:.>17} ".format(self.info['Name'])) print("Race{:.>17} ".format(self.info['Race'])) print("Level{:.>16} ".format(self.level)) print("Hit Points{:.>11} ".format(self.hp)) print("Gold Pieces{:.>10} ".format(self.gold)) print("Experience{:.>11} ".format(self.exp)) print("Next Level{:.>11} ".format(self.next_level_at)) press_enter() def show_inventory(self): """Prints player inventory screen""" clear_screen() # you have this redundant usage of player items. You could just access weapon # and armor info directly from the objects themselves, but instead you're doing 'inventory'. print("# INVENTORY #\n") print("Weapon{:.>17} ".format(self.weapon.name + self.weapon.icon)) print("Armor{:.>18} ".format(self.armor.name)) print("Items{:.>18} ".format(self.items[0])) # how to show all list items here ? print() print("# POTIONS #\n") count = 1 for potion in self.potions: print('#{} {}'.format(count, potion)) count += 1 press_enter() def reset_player(self): """reset the player, triggered on exit of active game""" # this will probably need modification once saving and loading are introduced! self.player_location = [(self.settings.grid_size - 1), (int(self.settings.grid_size / 2) - 1)] self.level = 1 self.hp = 10 self.max_hp = 10 self.gold = 10 self.exp = 0 self.next_level_at = self.get_level_up_val() self.potions = [] self.weapon = Weapon('Dagger', 4) self.armor = Armor('Leather', 10) self.dead = False class Monster(): """Generate a monster object for battle sequences, diff parameter determines difficulty""" def __init__(self, difficulty): self.difficulty = difficulty # add some randomization of difficulty here self.diff_string = self.get_diff_string() self.dice = Dice() # constructs a die object by calling Dice class self.advantage = False # determines who gets first attack, player or monster self.damage_roll = self.get_damage_roll() self.armor_class = self.get_armor_class() self.name = self.get_monster_name() # gets random name on construction self.hp = self.get_hit_points() # gets HP depending on difficulty def get_armor_class(self): if self.difficulty == 1: return 7 if self.difficulty == 2: return 11 if self.difficulty == 3: return 14 if self.difficulty == 4: return 16 def get_diff_string(self): """gets appropriate string based on difficult level int""" if self.difficulty == 1: return 'EASY' if self.difficulty == 2: return 'MEDIUM' if self.difficulty == 3: return 'HARD' if self.difficulty > 3: return 'ELITE' def get_monster_name(self): """import name file, grab a name at random, return it -- all based on difficulty level""" if self.difficulty == 1: filename = 'text_files/easy_monsters.txt' with open(filename, encoding='utf-8') as file_object: monster_names = file_object.read().split() index = randint(0, len(monster_names) - 1) return monster_names[index] elif self.difficulty == 2: filename = 'text_files/medium_monsters.txt' with open(filename, encoding='utf-8') as file_object: monster_names = file_object.read().split() index = randint(0, len(monster_names) - 1) return monster_names[index] elif self.difficulty == 3: filename = 'text_files/hard_monsters.txt' with open(filename, encoding='utf-8') as file_object: monster_names = file_object.read().split() index = randint(0, len(monster_names) - 1) return monster_names[index] elif self.difficulty > 3: filename = 'text_files/elite_monsters.txt' with open(filename, encoding='utf-8') as file_object: monster_names = file_object.read().split() index = randint(0, len(monster_names) - 1) return monster_names[index] def get_hit_points(self): if self.difficulty == 1: return self.dice.roll(4) elif self.difficulty == 2: return ((self.dice.roll(6)) + 2) elif self.difficulty == 3: return ((self.dice.roll(10)) + 4) elif self.difficulty > 3: return ((self.dice.roll(20)) + 10) def print_stats(self): print('# MONSTER STATS #') #23 chars print('NAME:{:.>18}'.format(self.monster_name.upper())) print('DIFF LEVEL:{:.>12}'.format(self.diff_string)) print('HP:{:.>20}'.format(self.hp)) print('AC:{:.>20}'.format(self.ac)) print() def get_damage_roll(self): """determine damage roll of monster via difficulty level""" if self.difficulty == 1: return 4 if self.difficulty == 2: return 6 if self.difficulty == 3: return 8 if self.difficulty > 3: return 10 class GameLog(): """an object that contains the game log and displays its contents as necessary""" def __init__(self, player, grid): self.player = player self.grid = grid self.room_book = self.make_room_book() self.room_book_visited = self.make_room_book_visited() self.current_room = 'None' # used only to print room type in game header self.current_message = 'None' def update_log(self): """update the game_log to get current room from updated grid""" self.current_room = self.grid.current_room_type #a bit redundant, you could access grid object to print header info. self.current_message = self.get_current_message() def get_current_message(self): """looks at grid object to determine and return appropriate log entry""" # this is where you use the room_status attribute bool, you COULD simply check the all_room_grid bool # 'Visited' here instead, it's the same info. You just thought having this extra var was cleaner. if self.grid.room_status == False and self.grid.current_room_type != 'Exit': if self.grid.current_room_type == 'Start': self.current_message = self.room_book['Start'] elif self.grid.current_room_type == 'Empty': self.current_message = self.room_book['Empty'] elif self.grid.current_room_type == 'Monster': self.current_message = self.room_book['Monster'] elif self.grid.current_room_type == 'Treasure': self.current_message = self.room_book['Treasure'] elif self.grid.current_room_type == 'Mystic': self.current_message = self.room_book['Mystic'] # do you really need to separate the exit text like this? elif self.grid.current_room_type == 'Exit': # doesn't matter if Visited is True or False, Exit always presents the same. self.current_message = self.room_book['Exit'] # room_status = True, room has already been visited: use the visited dictionary of texts. else: if self.grid.current_room_type == 'Start': self.current_message = self.room_book_visited['Start'] elif self.grid.current_room_type == 'Empty': self.current_message = self.room_book_visited['Empty'] elif self.grid.current_room_type == 'Monster': self.current_message = self.room_book_visited['Monster'] elif self.grid.current_room_type == 'Treasure': self.current_message = self.room_book_visited['Treasure'] elif self.grid.current_room_type == 'Mystic': self.current_message = self.room_book_visited['Mystic'] return self.current_message def print_log(self): """prints the header, the current dungeon grid, and the current log text entry""" # print header stats print('{} the {} \t HP: {} GOLD: {} EXP: {}\t ROOM: {}'.format(self.player.info['Name'].upper(), self.player.info['Race'], \ self.player.hp, self.player.gold, self.player.exp, self.current_room)) # print game map self.grid.print_grid() # game log print(self.current_message) def make_room_book(self): """assign a dictionary of room text to room_book attribute""" filename = 'text_files/room_book.txt' with open(filename, encoding='utf-8') as file_object: room_text = file_object.read().split('X') room_dict = { 'Start':room_text[0], 'Empty':room_text[1], 'Monster':room_text[2], 'Treasure':room_text[3], 'Mystic':room_text[4], 'Exit':room_text[5], } return room_dict def make_room_book_visited(self): """make the dictionary object of room text for already visited rooms""" filename = 'text_files/room_book_visited.txt' with open(filename, encoding='utf-8') as file_object: room_text_b = file_object.read().split('X') room_dict_b = { 'Start':room_text_b[0], 'Empty':room_text_b[1], 'Monster':room_text_b[2], 'Treasure':room_text_b[3], 'Mystic':room_text_b[4], 'Exit':room_text_b[5], } return room_dict_b class MainMenu(): """Display menu and receive input for user choice""" def __init__(self): self.nothing = None def print_menu(self): clear_screen() print('# DEEPER DUNGEONS #\n') print('1. Start New Game') print('2. Load Game') print('3. Change Game Settings') print('4. Exit Game') def main_choice(self): possible_choices = ['1','2','3','4'] active = True while active: msg = '\nEnter your choice: ' choice = input(msg) if choice in possible_choices: active = False return int(choice) # is active = False redundant since the return will exit the loop and function? else: print('That\'s not one of the menu options!') # define game UI functions. def you_are_dead(player, text=''): if text: print(text) print('YOU', end='', flush=True) time.sleep(0.5) print('\tARE', end='', flush=True) time.sleep(0.5) print('\tDEAD.', end='', flush=True) print('So passes {} the {} into the endless night.'.format(player.info['Name'], player.info['Race'])) press_enter() def step_printer(word, speed=0.06): """call whenever you want to print a word in steps""" #not modifying the word, so no need to index it for c in word: print(c, end='', flush=True) time.sleep(speed) # old index version #for c in range(len(word)): # print(word[c], end='', flush=True) # time.sleep(speed) def slow_print_two(word_one, word_two): """call to print one word, pause, then the second word""" print(word_one, end='', flush=True) time.sleep(0.08) print(word_two) def slow_print_elipsis(word_one, word_two, elip=6): """prints word one, then step prints elipsis, then prints word two""" elipsis = ('.' * elip) print(word_one, end='', flush=True) for c in elipsis: print(c, end='', flush=True) time.sleep(0.06) print(word_two, flush=True) def command_menu(player): """prints the command menu for the player""" clear_screen() print('#{:^33}#'.format(player.info['Name'].upper() + '\'s COMMANDS')) print() print('MOVE: North DO: Rest GAME: Save') print(' South Item Quit') print(' East Bio') print(' West') print() print() print('Type the first letter of a command') print('at the game prompt (>).') press_enter() def main_menu(player): """displays main program menu, takes user input choice and returns it""" clear_screen() print('# DEEPER DUNGEONS #\n') print('1. Build character') print('2. Start New Game') print('3. Load Game') print('4. Change Game Settings') print('5. Exit Game') print('\nCurrently Loaded Character: {}'.format(player.info['Name'])) possible_choices = ['1','2','3','4','5'] msg = '\nEnter your choice: ' choice = input(msg) if choice in possible_choices: return int(choice) else: print('That\'s not one of the menu options!') press_enter() return None # no loop is necessary in this function because run_game's call to this func gets None, # therefore has no other action to perform, so it (run_game body loop) loops, calling # this function again. def get_player_input(): msg = '\n> ' player_input = input(msg) return player_input def get_input_valid(text=None, key='standard'): """a version of input function that also performs input validation""" # always put key=... in a call to this function if text: print(text) command = '' # initialize command as empty string # not necessary, but clean... possible_choices = get_possible_choices(key) valid = False while not valid: command = input('\n> ') if command not in possible_choices: print('You did not enter a valid command, try again.') else: valid = True return command def get_possible_choices(key): #possible_choices = [] if key == 'standard': possible_choices = ['n','s','e','w','i','b','c','d','q'] elif key == 'battle': possible_choices = ['attack','standard','headshot','s','h','c','p','i','b'] possible_choices += ['finesse','fin','flurry','flu'] # you need to add the menu options for battle mode: commands, potions, items, etc. # think of it like this: this place is the 'master set' of valid commands. # inside the actual game functions, you will parse the inputs to perform the # corresponding actions, *always knowing that a valid command has already been # entered*. # add more as needed here return possible_choices def press_enter(text=None): if text: print(text) msg = '\n...' input(msg) def clear_screen(): """simple command to clear the game screen""" print("\033[H\033[J") # define main 'game in play' functions def action_menu(game_log): """print the game_log, the map, the command menu, take user input, and Return user choice""" clear_screen() game_log.print_log() # this is THE print command of the game header -and- game map !! # if you want to create loops that keep header active, you'll either need to figure out # how and where to move this, or call it more than once. possible_choices = ['c', 'n', 's', 'e', 'w', 'r', 'i', 'b', 'q', 'd'] command = get_player_input().lower() if command in possible_choices: return command else: print('\nYou have entered an invalid command, try again.') press_enter() return None # note: the input validation performed here doesn't need to be in a while loop, because the # function that calls this function, game_action, has a while loop that essentially handles that. # if player gets the else statement above for invalid input, we fall back to game_action, which # has nothing left to do (command == None), so it loops, and this function is called again. def game_action(settings, player, grid, game_log, dice): grid.update_player_location() # needs to happen here initially so the X gets printed to board game_log.update_log() # same, needs to happen so its attributes are not in initial state 'None' active = True while active: # main game event loop for *game in state of play* (as opposed to game at main menu, not in play) command = action_menu(game_log) movement_choices = ['n','s', 'e', 'w'] if command in movement_choices: if movement_engine(settings, player, grid, command): # True response = player moved on board grid.update_player_location() grid.update_current_roomtype() game_log.update_log() # check if movement into new room triggers an event, and if so, trigger it. determine_next_event(settings, player, grid, game_log, command) elif command == 'i': """Show inventory screen""" player.show_inventory() elif command == 'b': """Show player info screen""" player.print_player_info() elif command == 'd': """show room types for each grid coordinate (dev only)""" grid.dev_grid_showtypes() elif command == 'c': """show player the available game commands they can use""" command_menu(player) elif command == 'q': print('Returning to Main Menu...') time.sleep(0.5) player.reset_player() #reset player so new game starts fresh, attributes back to initials #reset_grid() # I think this is not needed; grid is constructed when menu action 2 is chosen, so will be new. #reset_log() # same as grid active = False else: pass if check_player_status(settings, player): # if True, player is dead, end action event loop. active = False player.reset_player() # needs to be reset for new game start print('Returning to Main Menu...', flush=True) time.sleep(0.8) else: pass # need to perform checks here to see if player exited floor of dungeon on this turn. # if so, we need to udpate settings (difficulty, etc) and update grid to create the next level of the dungeon # Q: do we actually create a new dungeon object? or modify the existing one? which makes more sense? # if active: # in case anything else needs to happen here, but probably there shouldn't be. def check_player_status(settings, player): # seems we don't actually need settings ? """check in every pass of game action event loop to see if player status has changed in a way that triggers event""" # check if player is alive if player.hp <= 0: player.dead = True print('\nOh damn! Looks like {} has been defeated!'.format(player.info['Name'])) time.sleep(0.6) print('\nGAME',end='',flush=True) time.sleep(0.8) print(' OVER.') press_enter() return True # check if player has levelled up... surely this needs to be its own function, and probably a method of # the player class... if not player.dead: if player.exp >= player.next_level_at: player.level += 1 player.next_level_at = player.get_level_up_val() clear_screen() text = '**** {} LEVELS UP! ****'.format(player.info['Name'].upper()) step_printer(text, 0.04) time.sleep(0.8) print() print('\n{} is now Level {}. Awesome!'.format(player.info['Name'], player.level), flush=True) player.max_hp += 4 time.sleep(0.8) print('\nHP has been increased to {}'.format(player.hp)) press_enter() return False def run_game(settings, player): """prints Main Menu and takes user input""" active = True while active: #main event loop of program running (but game not in play) user_action = main_menu(player) if user_action == 5: print('\nThanks for playing Deeper Dungeons!') print() active = False elif user_action == 1: player.build_player() player.created = True elif user_action == 2: if player.created: # we create the game grid object here, so that it's a brand new grid whenever option 2 (start game) is chosen grid = GameGrid(settings, player) game_log = GameLog(player, grid) # player entered 2, so we call game_action, which is the main 'game in play' function: game_action(settings, player, grid, game_log, dice) # note all the locations the arguments in game_action() call are being drawn from... they're all over the place! # that's because of Python's weird scope rules. # you'd think, logically / organizationally, that this function (run_game) could only pass objects that had # already been passed to it. and yet....but read through it all again: dice is the only outlier! else: print('\nYou need to create a character first!') press_enter() elif user_action == 3 or user_action == 4: print('\nSorry, that part of the game is still being developed.') press_enter() def movement_engine(settings, player, grid, selection): player.previous_coords = player.player_location.copy() if selection == 'n' and player.player_location[0] > 0: player.player_location[0] -= 1 elif selection == 's' and player.player_location[0] < settings.grid_size - 1: player.player_location[0] += 1 elif selection == 'e' and player.player_location[1] < settings.grid_size - 1: player.player_location[1] += 1 elif selection == 'w' and player.player_location[1] > 0: player.player_location[1] -= 1 # remember, the whole reason for the boolean return from this function is to separate between a # successful move (return true, grid update) and a border collision (return false, no grid update) else: print('\nYou\'ve hit the boundary of the dungeon!') press_enter() return False # false returned, so grid will not be updated; function exited here. grid.all_room_grid[player.previous_coords[0]][player.previous_coords[1]]['Visited'] = True return True def determine_next_event(settings, player, grid, game_log, command): """determine event that should occur on entering Room, and trigger that event""" direction = '' if command.lower() == 'n': direction = 'North' elif command.lower() == 's': direction = 'South' elif command.lower() == 'w': direction = 'West' elif command.lower() == 'e': direction = 'East' # we could look directly at the room dictionary stored in the all_room_grid, but it's less code to simply # look at the 'current_room_type' attribute of the grid, which is based on that same info anyway. move_text = ('Moving {}'.format(direction.title())) slow_print_elipsis(move_text, '', 4) if grid.current_room_type == 'Empty' and grid.room_status != True: # bypass print for already visited rooms. slow_print_elipsis('This room', 'is EMPTY.') time.sleep(0.8) elif grid.current_room_type == 'Treasure' and grid.room_status != True: slow_print_elipsis('This room', 'has a TREASURE chest!') time.sleep(0.8) treasure_event(settings, player) elif grid.current_room_type == 'Exit' and grid.room_status != True: slow_print_elipsis('This room', 'has a staircase going DOWN!') time.sleep(0.8) exit_event() elif grid.current_room_type == 'Mystic' and grid.room_status != True: slow_print_elipsis('This room', 'has a MYSTIC!') time.sleep(0.8) mystic_event() elif grid.current_room_type == 'Monster' and grid.room_status != True: slow_print_elipsis('This room', 'has a MONSTER!') time.sleep(0.8) battle_event(settings, player, grid, game_log) else: slow_print_elipsis('This room', 'seems familiar.') time.sleep(0.8) # this else will only occur if the room being entered has already been visited. # define room event functions -- triggered on entering unvisited room. def treasure_event(settings, player): if settings.difficulty == 1: treasure_roll = randint(1, 5) if settings.difficulty > 1 and settings.difficulty < 3: treasure_roll = (randint(1, 8) + 2) if settings.difficulty > 3: treasure_roll = (randint(1, 10) + 3) step_printer('OPENING CHEST...') print('You found {} Gold Pieces inside!'.format(treasure_roll)) player.gold += treasure_roll time.sleep(0.6) print('{} GP +{}'.format(player.info['Name'], treasure_roll)) press_enter() def mystic_event(): clear_screen() print('A an apparition is forming in the center of this room...') time.sleep(0.8) print('It takes on a ghostly human shape, and speaks to you!') time.sleep(0.8) print('WOULD YOU LIKE TO BUY A MAGIC ELIXIR...?') response = get_player_input() press_enter() def exit_event(): print('An exit event is now triggered!') press_enter() def battle_event(settings, player, grid, game_log): # create a monster monster = Monster(settings.difficulty) encounter_monster(player, monster, grid, game_log) # define all Battle functions def encounter_monster(player, monster, grid, game_log): """monster is engaged and decision to fight or run is chosen by player""" clear_screen() # determine how difficult it is for player to run away successfully run_difficulty = int(randint(2,10) + (3 * monster.difficulty)) run_failed = False active = True # step print encounter text slow_print_elipsis('You have encountered a', monster.name.upper()) print('Run Difficulty: {}'.format(run_difficulty)) while active: command = get_player_input() possible_choices = ['fight', 'run', 'f', 'r'] if command not in possible_choices: print('You did not enter a valid command, try again.') else: # this if has no else case if command.lower().startswith('r'): if run_attempt(player, run_difficulty): # run was successful, exit encounter loop and do not start battle. active = False print('You successfully run away from the {}!'.format(monster.name)) time.sleep(0.8) print('You will now return to the previous room.') press_enter() # make current room (one being run out of) grid icon change back to a * grid.grid_matrix[player.player_location[0]][player.player_location[1]] = ' * ' # move player coords equal that of previously visited room player.player_location = player.previous_coords.copy() # update everything since room has reverted grid.update_player_location() grid.update_current_roomtype() game_log.update_log() # NOTE: Player never 'moved' (entered move command) to leave this room, we just # force them back in next lines. movement_engine() function is where previous room # gets set to Visited = True, but that will NOT have happened in this situation, # because they never 'moved' out of it. So, it should remain Visited = False, which # is actually what we want anyway. else: # will be used to have monster attack first run_failed = True print('You failed to run away from the {}!'.format(monster.name)) print('Now you must fight!') press_enter() if command.lower().startswith('f') or active: # end the encounter loop and start the battle active = False battle_main(player, monster, run_failed) def run_attempt(player, run_difficulty): """rolls player dice, prints out roll, returns True if roll beats run_dc, False otherwise""" roll = player.dice.roll(20) player.dice.print_roll() return (roll >= run_difficulty) # returns a bool def battle_main(player, monster, run_failed): turn = 0 round_num = 1 fight_mods = {'enemy_armor': 0, 'player_roll': 0, 'player_damage': 0} atype = {'attack': None} crits = {'crit': False} player_turn = True if run_failed: player_turn = False active = True while active: battle_header(player, monster, round_num) # player attack if player_turn: if player_attack(player, monster, fight_mods, round_num, crits, atype): if not crits['crit']: player_damage(player, monster, fight_mods, atype) else: pass player_turn = False # monster attack else: if monster.hp > 0: if monster_attack(player, monster, round_num): monster_damage(player, monster) player_turn = True # status check on both player and monster if check_battle_status(player, monster, crits): active = False # player or monster is dead, so end the battle loop. # run updates if the battle is still going if active: press_enter() # first of two calls to press_enter, for pause between ongoing loops turn += 1 if turn % 2 == 0: round_num += 1 crits['crit'] = False # reset crit. kinda inefficient. # reset the fight mods and atype so each round of battle starts with empty mods. fight_mods['enemy_armor'] = 0 fight_mods['player_roll'] = 0 fight_mods['player_damage'] = 0 atype['attack'] = None elif not active: # shouldn't this be the same result as just 'else'? but it didn't work... print('The battle is over!') press_enter() # second of two calls to press_enter, for pause before ending battle sequence. # clear_screen() def print_battle_commands(): """print a screen showing all possible commands in battle""" clear_screen() print('***** ATTACK TYPES *****') # 31 characters used print() print('STANDARD (S):') print('A normal attack. No mods to attack or damage rolls.') print() print('HEADSHOT (H):') print('Aim for the head! Enemy AC gets +4 but if you hit,') print('you deal double damage.') print() print('FLURRY (FLU):') print('Run in mad and flailing! Easier to hit enemy (Roll +3),') print('but you usually deal less damage: damage roll gets a') print('random 0 to 3 penalty.') print() print('FINESSE (FIN):') print('A deliberate attack, going for a weak point. Slightly') print('harder to hit (Enemy AC +2) but success means +2 to ') print('your damage roll.') print('\n') print('Type the name (or shortcut) of attack to enter command.') print() press_enter() def battle_header(player, monster, round_num): clear_screen() print('ROUND: {}'.format(round_num)) print('{: <12} \t HP: {: <3} AC: {: <3} \t WEP: {}{}'.format(player.info['Name'].upper(), player.hp, player.armor.armor_class, player.weapon.name, player.weapon.icon)) print('{: <12} \t HP: {: <3} AC: {: <3}'.format(monster.name.upper(), monster.hp, monster.armor_class)) print() def check_battle_status(player, monster, crits): """checks state of player and monster to determine if battle is over, or should continue""" #check player if player.hp <= 0: print('\nYou have been defeated by the {}!'.format(monster.name)) player.dead = True time.sleep(0.8) return True elif monster.hp <= 0: if not crits['crit']: print('\nYou have destroyed the {}!'.format(monster.name)) else: print() # this may not be necessary, need to playtest on critical hit success for line spacing. time.sleep(0.8) gain_exp(player, monster) time.sleep(0.8) return True else: # neither player nor monster has been defeated, fight will continue. return False def player_attack(player, monster, fight_mods, round_num, crits, atype): """runs all player attack functions and returns a bool to call in battle_main function""" command = attack_menu_input(player, monster, fight_mods, round_num) # if applicable, fight_mods will be updated by this call compute_attack_mods(player, monster, fight_mods, command, atype) # compute_potion_mods(player) # here is the actual attack die roll... roll = player.dice.roll(20) player.dice.print_roll() # check if roll is a critical hit if roll == 20: print('CRITICAL HIT!') print('The {} has been destroyed by your perfectly placed strike!'.format(monster.name)) monster.hp = 0 crits['crit'] = True # used as flag to skip damage roll after critical hit return True # check if there are fight mods to Player Roll to display on screen # note: headshot doesn't appear here because it mods Enemy AC, not the player roll! if atype['attack'] == 'flurry' and not crits['crit']: # don't show mods on a critical hit total = roll + fight_mods['player_roll'] time.sleep(0.6) print('+{} ({})'.format(fight_mods['player_roll'], 'flurry bonus')) time.sleep(0.6) print('= {}'.format(total)) elif (atype['attack'] == 'finesse' or atype['attack'] == 'standard') and not crits['crit']: pass # no mods to Player Roll on a standard or finesse attack. # check if hit was successul or not if roll + fight_mods['player_roll'] >= monster.armor_class + fight_mods['enemy_armor']: print('You successfully hit the {} with your {}!'.format(monster.name, player.weapon.name)) return True else: print('Your attack missed the {}, dang!'.format(monster.name)) return False def attack_menu_input(player, monster, fight_mods, round_num): """gets player input for player attack in a battle""" command = '' # again, just for C style initialization; not necessary active = True while active: battle_header(player, monster, round_num) # called because menu calls will clear screen print('Choose your attack...') command = get_input_valid(key='battle') # accessing menu keeps loop running; any other input exits loop and proceeds to attack if command == 'c': print_battle_commands() elif command == 'p': print('This is how you will use a potion, eventually.') press_enter() elif command == 'i': print('This would show player inventory.') press_enter() elif command == 'b': print('And this would show player bio....') press_enter() else: active = False # non-menu command entered, exit loop so battle can proceed. return command def compute_attack_mods(player, monster, fight_mods, command, atype): attack_words = ['standard','s','attack'] # all result in standard attack # headshot if command.lower() == 'headshot' or command.lower() == 'h': atype['attack'] = 'headshot' fight_mods['enemy_armor'] = 4 fight_mods['player_damage'] = 5 print('Headshot attempt!') time.sleep(0.6) print('The {}\'s AC is increased to {} on this attack!'.format(monster.name, monster.armor_class + fight_mods['enemy_armor'])) time.sleep(0.6) elif command.lower() == 'finesse' or command.lower() == 'fin': atype['attack'] = 'finesse' fight_mods['enemy_armor'] = 2 fight_mods['player_damage'] = 2 print('Finesse attack!') time.sleep(0.6) print('The {}\'s AC is increased to {} on this attack.'.format(monster.name, monster.armor_class + fight_mods['enemy_armor'])) time.sleep(0.6) elif command.lower() == 'flurry' or command.lower() == 'flu': atype['attack'] = 'flurry' damage_penalty = randint(0, 3) fight_mods['player_roll'] = 3 fight_mods['player_damage'] = (-damage_penalty) print('Flurry attack!') time.sleep(0.6) print('Attack roll will get +{} but damage will get -{}'.format(fight_mods['player_roll'], damage_penalty)) time.sleep(0.6) # normal attack; could use 'else' but I might add more possible choices later. elif command.lower() in attack_words: atype['attack'] = 'standard' #print('Standard attack') #time.sleep(0.6) def player_damage(player, monster, fight_mods, atype): # non-headshot attack damage roll if atype['attack'] != 'headshot': damage = player.dice.roll(player.weapon.damage) + fight_mods['player_damage'] # prevent negative damage from flurry + a low roll if damage <= 0: damage = 1 # headshot damage roll (different because it's the only one with multiplication) else: damage = player.dice.roll(player.weapon.damage) * 2 # print damage roll player.dice.print_roll() if atype['attack'] == 'headshot': time.sleep(0.6) print('x2 (headshot bonus)') time.sleep(0.6) print('= {}'.format(damage)) elif atype['attack'] == 'flurry' and fight_mods['player_damage'] != 0: time.sleep(0.6) print('{} (flurry penalty)'.format(fight_mods['player_damage'])) time.sleep(0.6) print('= {}'.format(damage)) elif atype['attack'] == 'finesse': time.sleep(0.6) print('+{} (finesse bonus)'.format(fight_mods['player_damage'])) time.sleep(0.6) print('= {}'.format(damage)) else: pass # standard attack prints no modifiers print('You dealt {} points of damage to the {}'.format(damage, monster.name.upper())) monster.hp -= damage # this is here simply so the header doesn't show a negative number for monster hp # after monster is defeated. if monster.hp < 0: monster.hp = 0 def monster_attack(player, monster, round_num): # put here to be consistent with player attack battle_header(player, monster, round_num) print('The {} is attacking you!'.format(monster.name)) # time.sleep() here ? roll = monster.dice.roll(20) monster.dice.print_roll() if roll == 20: print('CRITICAL HIT, OUCH!') print('Automatic 5 points of damage, plus normal damage roll.') player.hp -= 5 return True if roll > player.armor.armor_class: print('The {}\'s attack hits you!'.format(monster.name)) return True else: print('The {}\'s attack misses you, phew!'.format(monster.name)) return False def monster_damage(player, monster): damage = monster.dice.roll(monster.damage_roll) monster.dice.print_roll() print('You take {} points of damage!'.format(damage)) player.hp -= damage def gain_exp(player, monster): """award experience to player for beating a monster""" exp = ((monster.difficulty * 10) + randint(0,10)) player.exp += exp #any gain of exp always prints a message about the gain...might need to decouple the two. print('You gained {} experience points.'.format(exp)) time.sleep(0.08) # instantiate game objects # how do I make these not be global variables? should I have a 'build start objects' function # that is called before run_game? settings = GameSettings() player = Player(settings) dice = Dice() # call the main run_game function loop run_game(settings, player)
810cdf77367004f7764c0de8e6af34d7253011fd
m-hollow/deeper_dungeons
/old_files (archive)/determine_event.py
1,074
3.53125
4
from random import randint from random import choice import time def determine_event(current_room): """look at current room type and determine event that results""" if current_room == 'Empty': pass if current_room == 'Monster': monster_event(settings, player) if current_room == 'Treasure': treasure_event(player) if current_room == 'Exit': exit_event() if current_room == 'Mystic': mystic_event(player) def treasure_event(settings, player, dice): """the harder the level is, the more gold added; this is to balance play""" # note: this mod system isn't very good, currently. the idea is to increase # how much gold a treasure room gives as the dungeon levels increase. gold_mod = None if settings.difficulty == 1: gold_mod = 0 if settings.difficulty > 1 and settings.difficulty < 3 gold_mod = dice.rolldie(3) if settings.difficulty > 3 gold_mod = dice.roldie(5) base_gold = (dice.rolldie(10) + gold_mod) player.stats['GOLD'] += base_gold print('You found {} pieces of Gold!'.format(base_gold)) def mystic_event(settings, player):
3f40d22f79ba711e9ff154e109338d58804f2256
m-hollow/deeper_dungeons
/old_files (archive)/dungeon_more_old/ui_functions.py
3,901
3.765625
4
import time from random import randint, choice import copy # define game UI functions. def you_are_dead(player, text=''): if text: print(text) print('YOU', end='', flush=True) time.sleep(0.5) print('\tARE', end='', flush=True) time.sleep(0.5) print('\tDEAD.', end='', flush=True) print('So passes {} the {} into the endless night.'.format(player.info['Name'], player.info['Race'])) press_enter() def step_printer(word, speed=0.06): """call whenever you want to print a word in steps""" #not modifying the word, so no need to index it for c in word: print(c, end='', flush=True) time.sleep(speed) # old index version #for c in range(len(word)): # print(word[c], end='', flush=True) # time.sleep(speed) def slow_print_two(word_one, word_two): """call to print one word, pause, then the second word""" print(word_one, end='', flush=True) time.sleep(0.08) print(word_two) def slow_print_elipsis(word_one, word_two, elip=6): """prints word one, then step prints elipsis, then prints word two""" elipsis = ('.' * elip) print(word_one, end='', flush=True) for c in elipsis: print(c, end='', flush=True) time.sleep(0.06) print(word_two, flush=True) def command_menu(player): """prints the command menu for the player""" clear_screen() print('#{:^33}#'.format(player.info['Name'].upper() + '\'s COMMANDS')) print() print('MOVE: North DO: Rest GAME: Save') print(' South Item Quit') print(' East Bio') print(' West') print() print() print('Type the first letter of a command') print('at the game prompt (>).') press_enter() def main_menu(player): """displays main program menu, takes user input choice and returns it""" clear_screen() print('# DEEPER DUNGEONS #\n') print('1. Build character') print('2. Start New Game') print('3. Load Game') print('4. Change Game Settings') print('5. Exit Game') print('\nCurrently Loaded Character: {}'.format(player.info['Name'])) possible_choices = ['1','2','3','4','5'] msg = '\nEnter your choice: ' choice = input(msg) if choice in possible_choices: return int(choice) else: print('That\'s not one of the menu options!') press_enter() return None # no loop is necessary in this function because run_game's call to this func gets None, # therefore has no other action to perform, so it (run_game body loop) loops, calling # this function again. def get_player_input(): msg = '\n> ' player_input = input(msg) return player_input def get_input_valid(text=None, key='standard'): """a version of input function that also performs input validation""" # always put key=... in a call to this function if text: print(text) command = '' # initialize command as empty string # not necessary, but clean... possible_choices = get_possible_choices(key) valid = False while not valid: command = input('\n> ') if command not in possible_choices: print('You did not enter a valid command, try again.') else: valid = True return command def get_possible_choices(key): #possible_choices = [] if key == 'standard': possible_choices = ['n','s','e','w','i','b','c','d','q'] elif key == 'battle': possible_choices = ['attack','standard','headshot','s','h','c','p','i','b'] possible_choices += ['finesse','fin','flurry','flu'] # you need to add the menu options for battle mode: commands, potions, items, etc. # think of it like this: this place is the 'master set' of valid commands. # inside the actual game functions, you will parse the inputs to perform the # corresponding actions, *always knowing that a valid command has already been # entered*. # add more as needed here return possible_choices def press_enter(text=None): if text: print(text) msg = '\n...' input(msg) def clear_screen(): """simple command to clear the game screen""" print("\033[H\033[J")
b1080291935da258c1711e9980f70ab10dbe28cc
m-hollow/deeper_dungeons
/old_files (archive)/encounter_work.py
1,846
3.90625
4
from random import randint from random import choice import time def user_input(): msg = '> ' choice = input(msg) return choice def press_enter(): msg = '...' input(msg) def run_attempt(): escape_num = 10 # this will be determined by mosnster difficulty in actual game print('Press enter to roll your Run attempt') press_enter() roll = randint(1,20) if roll > escape_num: print('You rolled {}. You have successfully run away!'.format(roll)) return True else: print('You rolled {}. You failed to get away, now you must fight!'.format(roll)) return False def encounter(): """this works. it may be a bit janky. is there a way to divide into two functions?""" active = True run_failed = False # put a clear_screen() here print('You have encountered a MONSTER!') print('Will you fight or run?') while active: command = user_input() possible_choices = ['fight', 'run', 'f', 'r'] if command not in possible_choices: print('You did not enter a valid command, try again.') else: if command == 'r' or command == 'run': if run_attempt(): # successful run, needs to exit the entire while loop. # works because run_failed will still == False, so next if will not execute. active = False else: run_failed = True if (command == 'f' or command == 'fight') or run_failed == True: active = False battle() # clarify proper order of operations here, set active then call function? # or the other way around ? # some new function to check if battle is starting, and if so, calls battle, and if not, return to 'main' area # of game? only purpose would be so that battle() is not called from within the encounter() function, but # does it matter? isn't adding -more- code best avoided? def battle(): print('The battle begins now!') encounter()
566276fb5aa5e56e446404520131bff5b19a6a91
arumsey93/py-class
/pizzajoin.py
624
3.640625
4
class Pizza: def __init__(self): self.size = 0 self.style = "" self.new_topping = [] def add_topping(self, topping): self.new_topping.append(topping) def print_order(self): space = " and " new_string = f"I would like a {self.size}-inch, {self.style} pizza" if self.new_topping: new_string += f" with {space.join(self.new_topping)}" print(new_string) meat_lovers = Pizza() meat_lovers.size = 16 meat_lovers.style = "Deep dish" meat_lovers.add_topping("Pepperoni") meat_lovers.add_topping("Olives") meat_lovers.print_order()
e442af8261e751871962eaedc86d8afc61156284
irina-baeva/algorithms-with-python
/algorithms/big-o-complexity/constant_linear-complexity.py
507
3.96875
4
# Constant complexity example # O(1) - the same time no matter how much input def sum(a, b, c): return a + b + c print(sum(3,2,1)) # takes the same time as: print(sum(1000,300,111)) # Linear complexity example # O(n) - grows with the input 1:1 foodArray = ['pizza', 'burger', 'sushi', 'curry'] def findFoodInTheApp(arrayOfFood, desiredFood): for food in arrayOfFood: if food == desiredFood: return f'Here is your {food}' print(findFoodInTheApp(foodArray, 'curry')) # O(n)
7cafa9fc6b348af6d2f11ad8771c5cca59b1bea7
irina-baeva/algorithms-with-python
/data-structure/stack.py
1,702
4.15625
4
'''Imlementing stack based on linked list''' class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def insert_first(self, new_element): "Insert new element as the head of the LinkedList" new_element.next = self.head self.head = new_element def delete_first(self): "Delete the first (head) element in the LinkedList as return it" if self.head: deleted_element = self.head temp = deleted_element.next self.head = temp return deleted_element else: return None class Stack(object): def __init__(self,top=None): self.ll = LinkedList(top) def push(self, new_element): "Push (add) a new element onto the top of the stack" self.ll.insert_first(new_element) def pop(self): "Pop (remove) the first element off the top of the stack and return it" return self.ll.delete_first() # Test cases # Set up some Elements e1 = Element(5) e2 = Element(20) e3 = Element(30) e4 = Element(40) # Start setting up a Stack stack = Stack(e1) # Test stack functionality stack.push(e2) stack.push(e3) print(stack.pop().value) #30 print (stack.pop().value) #20 print (stack.pop().value) # 5 print (stack.pop()) stack.push(e4) print (stack.pop().value)
12e37d46b3b3b1dbcac643020f6faa1c28202d70
amitesh1201/Python_30Days
/day1_ex03.py
193
4.28125
4
# Calculate and print the area of a circle with a radius of 5 units. You can be as accurate as you like with the value of pi. pi = 3.14 radius = 5 area = pi * radius ** 2 print("Area: ", area)
c022ad739dbd4634b682b04f4036a18014b6283f
amitesh1201/Python_30Days
/OldPrgms/Day4_Ex2.py
437
3.921875
4
# 2. Use the input function to gather information about another movie. You need a title, director’s name, release year, and budget. movies = [ ("The Room", "Tommy Wiseau", "2003", "$6,000,000") ] title = input("Title: ") director = input("Director: ") year = input("Year of release: ") budget = input("Budget: ") # movies = input("Enter the movie name: "), input("Director: "), input("Release year: "), input("budget: ") # print(movies)
358227b3759aa81b96ea6b1e4be87e066be878ee
amitesh1201/Python_30Days
/day2_ex01.py
184
4.21875
4
# Ask the user for their name and age, assign theses values to two variables, and then print them. name = input("Enter your name: ") age = input("Enter your age: ") print(name, age)
01ece2001beaf028b52be310a8f1df24858f4e59
amitesh1201/Python_30Days
/OldPrgms/Day3_prc05.py
579
4.375
4
# Basic String Processing : four important options: lower, upper, capitalize, and title. # In order to use these methods, we just need to use the dot notation again, just like with format. print("Hello, World!".lower()) # "hello, world!" print("Hello, World!".upper()) # "HELLO, WORLD!" print("Hello, World!".capitalize()) # "Hello, world!" print("Hello, World!".title()) # "Hello, World!" # Use the strip method remto remove white space from the ends of a string print(" Hello, World! ".strip()) # "Hello, World!"
36ab5e0899e94be5d9ad720ace9341e4866a541c
amitesh1201/Python_30Days
/OldPrgms/Day4_Ex6.py
374
3.890625
4
# 6) Print both movies in the movies collection. movies = [ ("The Room", "Tommy Wiseau", "2003", "$6,000,000") ] title = input("Title: ") director = input("Director: ") year = input("Year of release: ") budget = input("Budget: ") new_movie = title, director, year, budget print(f"{new_movie[0]} ({new_movie[2]})") movies.append(new_movie) print(movies[0]) print(movies[1])
f138eb288de47bb1d2262157d93e1802f0e1252e
bolyb/CS361
/down_up.py
744
3.765625
4
class therapist: name = "" rank = "" __init__(self, set_name): name = set_name rank = 0 #Discription: #the votetally function is the crux of the task, the rest is used to showcase what the functionality is supposed to do. #This function takes in a user vote and a therapist to be voted on and manipulates the therapists rank. #Parameters: #The user vote should either be a 1 or -1 to increase or decrease the therapists rank. #The therapist class requires that there is a rank variable to associate the user vote to. def votetally(user_vote, a_therapist): a_therapist.rank = a_therapist.rank + user_vote def main: therapists = [] therapists.append(therapist("Bobby the psychic")) user_vote = 1 votetally(user_vote, therapist[0])
6b17d9aa0fb29c58334ed4cf199d972a62706301
Atabuzzaman/AI-code-with-Python
/waterJug.py
432
3.671875
4
def pour(jug1, jug2): print(jug1,'\t', jug2) if jug2 is 2: return elif jug2 is 4: pour(0, jug1) elif jug1 != 0 and jug2 is 0: pour(0, jug1) elif jug1 is 2: pour(jug1, 0) elif jug1 < 3: pour(3, jug2) elif jug1 < (4 - jug2): pour(0, (jug1 + jug2)) else: pour(jug1 - (4 - jug2), (4 - jug2) + jug2) print("JUG1\tJUG2") pour(0, 0)
980610302335d57bf25946c94f4bd2c7cc0eb97f
skidmarker/bugatti
/hash/42578.py
264
3.515625
4
def solution(clothes): answer = 1 c_dict = {} for c, type in clothes: if type in c_dict: c_dict[type] += 1 else: c_dict[type] = 1 for cnt in c_dict.values(): answer *= cnt + 1 return answer - 1
2417d550b5488eaec6800336beda0cbd8748a747
nataliaruzhytska/Password-generator
/src/app/api_pass/utils.py
2,597
3.59375
4
import random import string from flask import jsonify def random_chars(n=12, uppercase=False, symbol=False, digit=False): """ The function generates a random password using user-defined parameters and evaluates its difficulty :param n: str :param uppercase: bool :param symbol: bool :param digit: bool :return: str """ try: if not digit and not symbol and not uppercase: password = ''.join(random.choice(string.ascii_lowercase) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is too simple'}) elif not digit and not symbol: password = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is simple'}) elif uppercase and digit and not symbol: password = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is normal'}) elif uppercase and symbol and not digit: password = ''.join(random.choice('!@#$%^&*' + string.ascii_uppercase + string.ascii_lowercase) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is normal'}) elif digit and not uppercase and not symbol: password = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is simple'}) elif symbol and not digit and not uppercase: password = ''.join(random.choice('!@#$%^&*' + string.ascii_lowercase) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is simple'}) elif digit and symbol and not uppercase: password = ''.join(random.choice('!@#$%^&*' + string.ascii_lowercase + string.digits) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is normal'}) else: password = ''.join(random.choice('!@#$%^&*' + string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(int(n))) return jsonify({'password': password, 'message': 'Your password is OK!'}) except (ValueError, TypeError): return "Incorrect value! Check your input and try again"
f6c183fb7de25707619a330224cdfa841a8b44be
maryliateixeira/pyModulo01
/desafio005.py
229
4.15625
4
# Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e antecessor n= int(input('Digite um número:')) print('Analisando o número {}, o seu antecessor é {} e o sucessor {}' .format(n, (n-1), (n+1)))
13307a93bfccb71f40106daf37b2851a994ff070
maryliateixeira/pyModulo01
/desafio011.py
534
4.09375
4
#faça um programa que leia a altura e a largura de uma parede em metros, calcule sua area e a quantidade de tinta # necessária para pintá-la, sabendo que cada litro de tinha, pinta uma area de 2 metros quadrados larg= float(input('Digite a largura da parede em metros:')) alt = float(input('Digite a altura da parede em metros:')) area = larg * alt tinta = area / 2 print('Sua parede tem a dimensão de {}x{} e sua área é de {}m².'.format(larg, alt, area)) print('Para pintá-la é necessário {}L de tinta .'.format( tinta))
47ba0dd3e658857ff57767aa6b70bba17abce29e
ssiddoway/IT567
/port.py
5,137
3.609375
4
#!/usr/bin/python import sys, argparse, socket def main(): parser = argparse.ArgumentParser() parser.add_argument("-i","--input", help="Input file") parser.add_argument("-t", help="TCP port sccaner range, i.e. -t 1-1024") parser.add_argument("-u", help="UDP port scanner range, i.e. -u 1-1024") parser.add_argument("-d", help="Destination to run scan, i.e. -d 192.168.1.1") parser.add_argument("-D", help="Range of IP's given by CIDR / i.ie -D 192.168.1.0/24") args = parser.parse_args() # Given a list of IP address in a txt file if args.input: IPs = parseInputFile(args.input) if not args.t and not args.u: # User did not specify either TCP or UDP for ip in IPs: for port in range(1,1024): # Give standard port range scanTCP(ip,port) else: if args.t: # TCP for ip in IPs: tcpLoop(ip,args.t) print "" if args.u: # UDP for ip in IPs: udpLoop(ip,args.u) print "" # Range of IPs given by the / elif args.D: if not args.t and not args.u: # User did not specify either TCP or UDP for ip in IPs: for port in range(1,1024): # Give standard port range scanTCP(ip,port) else: if args.t: # TCP for ip in IPs: tcpLoop(ip,args.t) print "" if args.u: # UDP for ip in IPS: udpLoop(ip,args.u) print "" # Just a single remote desination else: if args.d: if not args.t and not args.u: # User did not specify either TCP or UDP for port in range(1,1024): # Give standard port range scanTCP(args.d,port) else: if args.t: # TCP tcpLoop(args.d,args.t) if args.u: # UDP udpLoop(args.d,args.u) else: print "Please provide a Remote host or a input file of hosts" def tcpLoop(IP,ports): portRange = ports.split('-') # Find the range of the tcp ports if len(portRange) > 1: for t in range(int(portRange[0]),int(portRange[1]) + 1): scanTCP(IP,int(t)) else: scanTCP(IP,int(ports)) def udpLoop(IP,ports): uPortRange = ports.split('-') # Find the range of the UDP ports) if len(uPortRange) > 1: for u in range(int(uPortRange[0]),int(uPortRange[1]) + 1): scanUDP(IP,int(u)) else: scanUDP(IP,int(ports)) def subnetCalculator(IP): temp = IP.split('/') subnet = temp[1] #Subnet CIDR IP = temp[0] #IP Address ipPortions = IP.split('.') #break up the IP into the octets exp = 32-int(subnet) #Exponent numOfIPs = 2 ** exp #Number of IPs start = ipPortions[3] #find Starting address end = int(start) + numOfIPs IPs = [] lastPortion = int(start) for i in range(0,numOfIPs): if lastPortion > 255: # last portion reached max lastPortion = 0 if ipPortions[2] == 255: # 2nd to last octet reached max ipPortions[2] = 0 if ipPortions[1] == 255: # 3rd to last octet reached max ipPortions[1] = int(ipPortions[1]) + 1 ipPortions[0] = int(ipPortions[0]) + 1 else: ipPortions[2] = int(ipPortions[2]) + 1 # increment 2nd to last octet up 1 tempIP = str(ipPortions[0]) + '.' + str(ipPortions[1]) + '.' + str(ipPortions[2]) + '.' + str(lastPortion) IPs.append(tempIP) lastPortion = lastPortion + 1 return IPs #Given a filepath or name this function will read line by line and create an array of IP addresses def parseInputFile(fileName): with open(fileName,'r') as f: content = [line.strip() for line in f if line.strip()] # Remove blank space and new line return content; # Return list of IPs #Given an IP address and Port this function will send a TCP packet to find if the port is listening def scanTCP(IP,Port): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.settimeout(1) result = sock.connect_ex((IP,Port)) if result == 0: print "IP:{} Port{}: Open".format(IP,Port) sock.close() #Given an IP address and Port this function will send a packet using UDP to find if the port is listening def scanUDP(IP,Port): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) try: s.sendto('ping'.encode(),(IP,Port)) s.recvfrom(1024) print "IP:{} Port{}: Open".format(IP,Port) except: s.close() s.close() if __name__ == "__main__": main()
067bba31d0f51150264914637f39224fe6d0cecd
renol767/python_Dasar
/DQLab/Kelas Persiapan/chartnamakelurahan.py
589
3.640625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt table = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/penduduk_gender_head.csv") table.head() x_label = table['NAMA KELURAHAN'] plt.bar(x=np.arange(len(x_label)), height=table['LAKI-LAKI WNI']) #Memberikan nilai axis dari data CSV plt.xticks(np.arange(len(x_label)), table['NAMA KELURAHAN'], rotation=90) #Menambah Title dan Label pada Grafik plt.xlabel('Kelurahan di Jakarta Pusat') plt.ylabel('Jumlah Penduduk Laki - Laki') plt.title('Persebaran Jumlah Penduduk Laki - Laki di Jakarta Pusat') plt.show()
f52d016e2684b8d6cfceb2366bd27331b4ddd71b
renol767/python_Dasar
/Latihan Python Dasar/35.3 Latihan Mengecek Suatu Password.py
360
3.625
4
def userx(): user = input("Masukan Username : ") if user == 'admin': print("Lanjut Gan, Masukin Passwordnya") pw = input("Masukan Password : ") if pw == 'admin': print("Login Sukses !") else: print("Password salah!") else: print("Salah Coy Usernamenya") return userx() userx()
2d7bfd605e1105eb79716bb0b93357760887bd4a
renol767/python_Dasar
/Latihan Python Dasar/Tutorialsebelumpackage/11 Return and Lambda.py
489
3.6875
4
# return a = 8 def kuadrat (a): total = a**2 print("Kuadrat dari",a,"adalah",total) return total a = kuadrat(a) print (a) print (50*'-') # return multiple argument def tambah (a,b): total = a+b print(a, "+" , b , '=', total) return total def kali (a,b): total = a*b print(a, "x" , b , "=", total) return total a = tambah(3,8) b = kali (2,tambah(7,8)) print(a) print(b) # function dengan lambda kali = lambda x,y : x*y print("Lambda Funct : ",kali(3,5))
047ca459460989c8c06d76cf16c341cee0e838a4
renol767/python_Dasar
/Latihan Python Dasar/35.4 Latihan Deret Fibonaci.py
154
3.953125
4
suku = int(input('Masukan Suku Ke Berapa : ')) a = 0 b = 1 c = 3 print(a) print(b) while c <= suku: c = a+b a = b b = c print(c) c+=1
3e3618fc47c05008bf92518dcd953d350c265918
avsingh999/rl-tictactoe
/tictactoe.py
10,944
4.0625
4
""" Reference implementation of the Tic-Tac-Toe value function learning agent described in Chapter 1 of "Reinforcement Learning: An Introduction" by Sutton and Barto. The agent contains a lookup table that maps states to values, where initial values are 1 for a win, 0 for a draw or loss, and 0.5 otherwise. At every move, the agent chooses either the maximum-value move (greedy) or, with some probability epsilon, a random move (exploratory); by default epsilon=0.1. The agent updates its value function (the lookup table) after every greedy move, following the equation: V(s) <- V(s) + alpha * [ V(s') - V(s) ] This particular implementation addresses the question posed in Exercise 1.1: What would happen if the RL agent taught itself via self-play? The result is that the agent learns only how to maximize its own potential payoff, without consideration for whether it is playing to a win or a draw. Even more to the point, the agent learns a myopic strategy where it basically has a single path that it wants to take to reach a winning state. If the path is blocked by the opponent, the values will then usually all become 0.5 and the player is effectively moving randomly. Created by Wesley Tansey 1/21/2013 Code released under the MIT license. """ import random from copy import copy, deepcopy import csv import matplotlib.pyplot as plt EMPTY = 0 PLAYER_X = 1 PLAYER_O = 2 DRAW = 3 BOARD_FORMAT = "----------------------------\n| {0} | {1} | {2} |\n|--------------------------|\n| {3} | {4} | {5} |\n|--------------------------|\n| {6} | {7} | {8} |\n----------------------------" NAMES = [' ', 'X', 'O'] def printboard(state): cells = [] for i in range(3): for j in range(3): cells.append(NAMES[state[i][j]].center(6)) print(BOARD_FORMAT.format(*cells)) def emptystate(): return [[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY]] def gameover(state): for i in range(3): if state[i][0] != EMPTY and state[i][0] == state[i][1] and state[i][0] == state[i][2]: return state[i][0] if state[0][i] != EMPTY and state[0][i] == state[1][i] and state[0][i] == state[2][i]: return state[0][i] if state[0][0] != EMPTY and state[0][0] == state[1][1] and state[0][0] == state[2][2]: return state[0][0] if state[0][2] != EMPTY and state[0][2] == state[1][1] and state[0][2] == state[2][0]: return state[0][2] for i in range(3): for j in range(3): if state[i][j] == EMPTY: return EMPTY return DRAW def last_to_act(state): countx = 0 counto = 0 for i in range(3): for j in range(3): if state[i][j] == PLAYER_X: countx += 1 elif state[i][j] == PLAYER_O: counto += 1 if countx == counto: return PLAYER_O if countx == (counto + 1): return PLAYER_X return -1 def enumstates(state, idx, agent): if idx > 8: player = last_to_act(state) if player == agent.player: agent.add(state) else: winner = gameover(state) if winner != EMPTY: return i = int(idx / 3) j = int(idx % 3) for val in range(3): state[i][j] = val enumstates(state, idx+1, agent) class Agent(object): def __init__(self, player, verbose = False, lossval = 0, learning = True): self.values = {} self.player = player self.verbose = verbose self.lossval = lossval self.learning = learning self.epsilon = 0.1 self.alpha = 0.99 self.prevstate = None self.prevscore = 0 self.count = 0 enumstates(emptystate(), 0, self) def episode_over(self, winner): self.backup(self.winnerval(winner)) self.prevstate = None self.prevscore = 0 def action(self, state): r = random.random() if r < self.epsilon: move = self.random(state) self.log('>>>>>>> Exploratory action: ' + str(move)) else: move = self.greedy(state) self.log('>>>>>>> Best action: ' + str(move)) state[move[0]][move[1]] = self.player self.prevstate = self.statetuple(state) self.prevscore = self.lookup(state) state[move[0]][move[1]] = EMPTY return move def random(self, state): available = [] for i in range(3): for j in range(3): if state[i][j] == EMPTY: available.append((i,j)) return random.choice(available) def greedy(self, state): maxval = -50000 maxmove = None if self.verbose: cells = [] for i in range(3): for j in range(3): if state[i][j] == EMPTY: state[i][j] = self.player val = self.lookup(state) state[i][j] = EMPTY if val > maxval: maxval = val maxmove = (i, j) if self.verbose: cells.append('{0:.3f}'.format(val).center(6)) elif self.verbose: cells.append(NAMES[state[i][j]].center(6)) if self.verbose: print(BOARD_FORMAT.format(*cells)) self.backup(maxval) return maxmove def backup(self, nextval): if self.prevstate != None and self.learning: self.values[self.prevstate] += self.alpha * (nextval - self.prevscore) def lookup(self, state): key = self.statetuple(state) if not key in self.values: self.add(key) return self.values[key] def add(self, state): winner = gameover(state) tup = self.statetuple(state) self.values[tup] = self.winnerval(winner) def winnerval(self, winner): if winner == self.player: return 1 elif winner == EMPTY: return 0.5 elif winner == DRAW: return 0 else: return self.lossval def printvalues(self): vals = deepcopy(self.values) for key in vals: state = [list(key[0]),list(key[1]),list(key[2])] cells = [] for i in range(3): for j in range(3): if state[i][j] == EMPTY: state[i][j] = self.player cells.append(str(self.lookup(state)).center(3)) state[i][j] = EMPTY else: cells.append(NAMES[state[i][j]].center(3)) print(BOARD_FORMAT.format(*cells)) def statetuple(self, state): return (tuple(state[0]),tuple(state[1]),tuple(state[2])) def log(self, s): if self.verbose: print(s) class Human(object): def __init__(self, player): self.player = player def action(self, state): printboard(state) action = input('Your move? i.e. x,y : ') return (int(action.split(',')[0]),int(action.split(',')[1])) def episode_over(self, winner): if winner == DRAW: print('Game over! It was a draw.') else: print('Game over! Winner: Player {0}'.format(winner)) def play(agent1, agent2): state = emptystate() for i in range(9): if i % 2 == 0: move = agent1.action(state) else: move = agent2.action(state) state[move[0]][move[1]] = (i % 2) + 1 winner = gameover(state) if winner != EMPTY: return winner return winner def measure_performance_vs_random(agent1, agent2): epsilon1 = agent1.epsilon epsilon2 = agent2.epsilon agent1.epsilon = 0 agent2.epsilon = 0 agent1.learning = False agent2.learning = False r1 = Agent(1) r2 = Agent(2) r1.epsilon = 1 r2.epsilon = 1 probs = [0,0,0,0,0,0] games = 100 for i in range(games): winner = play(agent1, r2) if winner == PLAYER_X: probs[0] += 1.0 / games elif winner == PLAYER_O: probs[1] += 1.0 / games else: probs[2] += 1.0 / games for i in range(games): winner = play(r1, agent2) if winner == PLAYER_O: probs[3] += 1.0 / games elif winner == PLAYER_X: probs[4] += 1.0 / games else: probs[5] += 1.0 / games agent1.epsilon = epsilon1 agent2.epsilon = epsilon2 agent1.learning = True agent2.learning = True return probs def measure_performance_vs_each_other(agent1, agent2): #epsilon1 = agent1.epsilon #epsilon2 = agent2.epsilon #agent1.epsilon = 0 #agent2.epsilon = 0 #agent1.learning = False #agent2.learning = False probs = [0,0,0] games = 100 for i in range(games): winner = play(agent1, agent2) if winner == PLAYER_X: probs[0] += 1.0 / games elif winner == PLAYER_O: probs[1] += 1.0 / games else: probs[2] += 1.0 / games #agent1.epsilon = epsilon1 #agent2.epsilon = epsilon2 #agent1.learning = True #agent2.learning = True return probs if __name__ == "__main__": p1 = Agent(1, lossval = -1) p2 = Agent(2, lossval = -1) r1 = Agent(1, learning = False) r2 = Agent(2, learning = False) r1.epsilon = 1 r2.epsilon = 1 series = ['P1-Win','P1-Lose','P1-Draw','P2-Win','P2-Lose','P2-Draw'] #series = ['P1-Win', 'P2-Win', 'Draw'] colors = ['r','b','g','c','m','b'] markers = ['+', '.', 'o', '*', '^', 's'] f = open('results.csv', 'w') writer = csv.writer(f) writer.writerow(series) perf = [[] for _ in range(len(series) + 1)] for i in range(10000): if i % 10 == 0: print('Game: {0}'.format(i)) probs = measure_performance_vs_random(p1, p2) writer.writerow(probs) f.flush() perf[0].append(i) for idx,x in enumerate(probs): perf[idx+1].append(x) winner = play(p1,p2) p1.episode_over(winner) #winner = play(r1,p2) p2.episode_over(winner) f.close() for i in range(1,len(perf)): plt.plot(perf[0], perf[i], label=series[i-1], color=colors[i-1]) plt.xlabel('Episodes') plt.ylabel('Probability') plt.title('RL Agent Performance vs. Random Agent\n({0} loss value, self-play)'.format(p1.lossval)) #plt.title('P1 Loss={0} vs. P2 Loss={1}'.format(p1.lossval, p2.lossval)) plt.legend() plt.show() #plt.savefig('p1loss{0}vsp2loss{1}.png'.format(p1.lossval, p2.lossval)) plt.savefig('selfplay_random_{0}loss.png'.format(p1.lossval)) while True: p2.verbose = True p1 = Human(1) winner = play(p1,p2) p1.episode_over(winner) p2.episode_over(winner)
a3fb45777567b8e29bb0b31fb734bcd1dc8579ca
mikeyhu/project-euler-python
/test/test_Problem1.py
374
3.8125
4
import unittest from main import Problem1 class TestProblem1(unittest.TestCase): def test_sum_of_natural_numbers_below_10_that_are_multiples_of_3_or_5(self): p1 = Problem1.Problem1() self.assertEqual(23,p1.solve(10)) def test_sum_of_natural_numbers_below_1000_that_are_multiples_of_3_or_5(self): p1 = Problem1.Problem1() self.assertEqual(233168,p1.solve(1000))
f003866db45687ef25b32772941b73413ae552cf
mikeyhu/project-euler-python
/main/Problem5.py
447
3.5
4
import itertools class Problem5(object): def solve(self,number): uniqueProducts = self.products(number) for x in itertools.count(1): valid = True for i in uniqueProducts: if not x % i == 0: valid = False if valid: return x def products(self,number): result = [] for i in range(number,1,-1): add = True for j in result: if j % i == 0: add = False if add: result.append(i) return result
8d19c27a48eef36d5924f38be89fee9a362d95bc
igorbustinza/theegg_ai
/tarea23/tarea23.py
7,606
3.703125
4
##Tarea 23 import random ##funciones ##función que cifra y descifra el texto def cifra_descifra(cifraTextoDescifra,listaCartasFuncion,operacion): #creamos un diccionario con las letras y su correpondiente valor valoresLetras = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26} ##función que devuelve el valor numérico del texto a cifrar/descifrar def valor_numerico_texto(textoCD): listaTxtNum=[] ##creamos un diccionario con las letras y su valor numérico numLetras = len(textoCD) ##vamos buscando el valor de cada letra for i in range(numLetras): valorLetra = valoresLetras.get(textoCD[i:i+1]) listaTxtNum.append(valorLetra) return listaTxtNum ##función que devuelve el texto cifrado correspondientes a una lista de valores numéricos def valor_texto_numerico(listaNumeros): ##pasamos a una lista las claves del diccionario y utilizamos el valor numérico como índice de la lista claves = list(valoresLetras.keys()) txtCifrado ='' for j in listaNumeros: txtCifrado = txtCifrado + claves[j-1] return txtCifrado ################################## ##función que ejecuta el algoritmo del solitario para sacar el valor numérico a sumar al valor numérico del texto def solitario(cifraTxtDescifra,listaCartasInicial): ristra = [] listaCartasBarajeada = listaCartasInicial for n in cifraTxtDescifra: ##Paso1 del agoritmo: Intercambiar Joker A con la carta que está debajo posicionJokerA = listaCartasBarajeada.index("Joker A") listaCartasBarajeada.remove("Joker A") listaCartasBarajeada.insert(posicionJokerA + 1,"Joker A") ##Paso 2 del agoritmo: intercambiar Joker B con la carta que está debajo de la que tiene debajo posicionJokerB = listaCartasBarajeada.index("Joker B") listaCartasBarajeada.remove("Joker B") listaCartasBarajeada.insert(posicionJokerB + 2,"Joker B") ##Paso 3 del algoritmo: cortamos la baraja en 3, intercambiando las cartas antes del primer comodín con las cartas que están detrás del segundo comodin. posicionJokerA = listaCartasBarajeada.index("Joker A") posicionJokerB = listaCartasBarajeada.index("Joker B") if posicionJokerA < posicionJokerB: primerComodin = posicionJokerA segundoComodin = posicionJokerB else: primerComodin = posicionJokerB segundoComodin = posicionJokerA listaCorte1 = listaCartasBarajeada[0:primerComodin] listaCorte2 = listaCartasBarajeada[segundoComodin + 1:54] ##pasamos el corte 2 a la parte de arriba indiceAinsertar = 0 for k in listaCorte2: listaCartasBarajeada.remove(k) listaCartasBarajeada.insert(indiceAinsertar,k) indiceAinsertar = indiceAinsertar + 1 ##pasamos el corte 1 for j in listaCorte1: listaCartasBarajeada.remove(j) listaCartasBarajeada.append(j) ##Paso 4 del agoritmo: buscamos la última carta de la baraja, buscamos su valor numérico, contamos desde la primera carta hasta ese valor numerico ultimaCarta = listaCartasBarajeada[53] valorUltimaCarta = barajaCartas[listaCartasBarajeada[53]] listaCorte3 = listaCartasBarajeada[0:valorUltimaCarta] listaCartasBarajeada.remove(listaCartasBarajeada[53]) ##pasamos el corte 1 for m in listaCorte3: listaCartasBarajeada.remove(m) listaCartasBarajeada.append(m) listaCartasBarajeada.append(ultimaCarta) ##Paso 5 del algoritmo; mira la primera carta y conviertela en numero, cuenta las cartas hasta ese número (la primera es el uno) primeraCarta = listaCartasBarajeada[0] valorPrimeraCarta = barajaCartas[listaCartasBarajeada[0]] CartaPaso5 = listaCartasBarajeada[valorPrimeraCarta] valorCartaPaso5 = barajaCartas[CartaPaso5] ristra.append(valorCartaPaso5) return ristra ##cuerpo de la función cifra_descifra ##llamamos a la función que nos devuelve el valor numérico del texto a cifrar valorTexto = valor_numerico_texto(cifraTextoDescifra) ##utilizamos el algoritmo del solitario para generar la ristra a sumar para conseguir el texto cifrado valorRistra = solitario(cifraTextoDescifra,listaCartasFuncion) ##Si operacion=1 estamos cifrando, por lo que sumamos los valores de las letras a cifrar con los valores que nos ha devuelto el algoritmo del solitario. ##Si operacion=0 estamos descifrando, por lo que restamos los valores de las letras a cifrar con los valores que nos ha devuelto el algoritmo del solitario. valorTextomasRistra = [] if operacion == 1: for i, w in enumerate(valorTexto): valorTextomasRistra.append(valorTexto[i] + valorRistra[i]) else: for i, w in enumerate(valorTexto): valorTextomasRistra.append(valorTexto[i] - valorRistra[i]) valorTextomasRistra2 = [] #Cómo tenemos 26 letras, si los valores que nos dan son superiores a 26 tenemos que restarle 26 y si son superiores a 52 tenemos que restarle 52 #Si estamos descifrando al restar la ristra al valor del texto a descifrar, si nos salen valores negativos tenemos que sumarle 26 (o 52) para tener un valor positivo. for v in valorTextomasRistra: valorCorregido = v if v > 26 and v <= 52: valorCorregido = v -26 elif v > 52: valorCorregido = v-52 elif v < 0: valorCorregido = v + 26 elif v < -52: valorCorregido = v+52 valorTextomasRistra2.append(valorCorregido) #la función devuelve el texto cifrado/descifrado return valor_texto_numerico(valorTextomasRistra2) ####################### ##construimos la baraja ##Palos de la baraja palosBaraja = ("Treboles","Diamantes","Corazones","Picas") ##creamos una lista con las cartas para barajearlas listaCartas = [] ##Valores de las cartas ## Treboles -- Su valor ## Diamantes -- su valor + 13 ## Corazones - su valor + 26 ## Picas -- su valor + 39 barajaCartas = {"Joker A":53,"Joker B":53} listaCartas = ["Joker A","Joker B"] for element in palosBaraja: for i in range(13): if element == "Treboles": valorASumar = 0 elif element == "Diamantes": valorASumar = 13 elif element == "Corazoness": valorASumar = 26 elif element == "Picas": valorASumar = 39 cartaBaraja = str(i+1) + element valor = barajaCartas.setdefault(cartaBaraja,i+1 + valorASumar) ##creamos una lista con las cartas de la baraja para despues "barajearla" listaCartas.append(cartaBaraja) ##barajeamos la baraja de cartas random.shuffle(listaCartas) #convertimos la lista barajeada en una tupla para posteriormente usar la misma lista con las cartas en el mismo orden. tuplaCartas = tuple(listaCartas) ##Pedimos al usuario que escriba el texto a cifrar textoAcifrar = input("Introduce el texto a cifrar: ") ##ponemos el texto en mayúsculas y quitamos los espacios textoAcifrar = textoAcifrar.upper() textoAcifrar0 = "" for t in textoAcifrar: if t != " ": textoAcifrar0 = textoAcifrar0 + t numeroDeLetras = len(textoAcifrar) #llamamos a la función que cifra el texto introducido txtCifrado = cifra_descifra(textoAcifrar0,listaCartas,1) print(textoAcifrar0 + " cifrado es: " + txtCifrado) #una vez cifrado preguntamos al usuario si quiere descifrar el texto cifrado respuesta = '' while respuesta not in ('S','N'): respuesta1 = input("¿Quieres descifrar " + txtCifrado + "? (S/N): ") respuesta = respuesta1.upper() if respuesta == 'N': ## No desciframos print("OK. Agur") else: #desciframos #volvemos a convertir la tupla en lista para utilizarla en el algoritmo del solitario listaCartas = list(tuplaCartas) txtDescifrado = cifra_descifra(txtCifrado,listaCartas,2) print(txtCifrado + " descifrado es: " + txtDescifrado)
b9151241f8234f5c1f038c733a5d0ff46da376d3
louishuynh/patterns
/observer/observer3.py
2,260
4.15625
4
""" Source: https://www.youtube.com/watch?v=87MNuBgeg34 We can have observable that can notify one group of subscribers for one kind of situation. Notify a different group of subscribers for different kind of situation. We can have the same subscribers in both groups. We call these situations events (different kinds of situations) or channels. This gives us the flexibility of how we notify subscribers. """ class Subscriber: """ Sample observer. """ def __init__(self, name): self.name = name def update(self, message): print('{} got message "{}"'.format(self.name, message)) class Publisher: def __init__(self, events): """ We want to provide interface that allows subscribers to register for a specific event that the observable can announce. So we modify a publisher to take several events and modify the subscriber attribute to map event names to strings to dictionaries that then map subscribers to their callback function """ self.subscribers = {event: dict() for event in events} def get_subscribers(self, event): """ Helper method. Look up for a given even the map of subscriber to the callback function. """ return self.subscribers[event] def register(self, event, who, callback=None): """ Change the way we insert the subscriber to our records of the callback.""" if callback is None: # fallback to original method callback = getattr(who, 'update') self.get_subscribers(event)[who] = callback def unregister(self, event, who): del self.get_subscribers(event)[who] def dispatch(self, event, message): """ We keep the api interface fairly similar.""" for subscriber, callback in self.get_subscribers(event).items(): callback(message) if __name__ == '__main__': pub = Publisher(['lunch', 'dinner']) bob = Subscriber('Bob') alice = Subscriber('Alice') john = Subscriber('John') pub.register("lunch", bob) pub.register("dinner", alice) pub.register("lunch", john) pub.register("dinner", john) pub.dispatch("lunch", "It's lunchtime!") pub.dispatch("dinner", "Dinner is served")
bb1e695e901d9f80fd97ac45ad64891229f2d79c
timmichanga13/python
/fundamentals/fundamentals/demos/data_types.py
1,411
4.03125
4
# many of the same types; booleans, values, strings # python interpreter is an environment where the computer can immediately implement code # use for testing/remembering if something works # booleans start with capital T and F #values are split between integers and floats # floats are imperfect representations # strings behave relatively the same, can use "" or '' # do not need to establish variables with var # automatically handles tedious actions # lists, tuples, and dictionaries # tuples are an immutable list (array) but cannot change definitions in it # tuples use () instead of [] # lists are a lot like arrays in JS (pretty much the same) # .push() becomes .append() # dictionaries are pairs of key-value pairs (object has a different meaning in python) # Loops # print 1 to 255 for x in range(1,101): print(x) print(x*x) # what happens inside a loop is identified by indentation # this print is outside of the loop print("Done!") # careful copying and pasting, check for tabs vs. spaces, they indent differently # if statements look a lot like for loops # list of names names = ["Sarah", 'jack', 'Beth', 'Jort'] # for loop to the length of the array for x in range(0, len(names)): # print the name at index x print(names[x]) # gives the same output # first part is arbitrary # the second part is important and tells you where to look for name in names: print(name)